#!/usr/bin/env groovy
pipeline {
  // The canonical certification jobs are scheduled on external-agent-2,
  // which provides the approved Python 3.12 toolchain through agent policy.
  agent { label 'external-agent-2' }
  options { disableConcurrentBuilds(); skipDefaultCheckout(true) }
  stages {
    stage('Checkout and build') {
      steps {
        checkout scm
        sh '''#!/usr/bin/env bash
          set -euo pipefail
          rm -rf .venv-wheel .venv-sdist dist build *.egg-info
          python3.12 -m compileall -q ocyan
          python3.12 -m venv .venv-build
          . .venv-build/bin/activate
          python -m pip install --upgrade pip build
          python -m build --wheel --sdist --outdir dist
          python -m pip install twine
          python -m twine check dist/*.whl dist/*.tar.gz
        '''
      }
    }
    stage('Wheel validation') {
      steps {
        sh '''#!/usr/bin/env bash
          set -euo pipefail
          python3.12 -m venv .venv-wheel
          . .venv-wheel/bin/activate
          python -m pip install --upgrade pip
          python -m pip install --index-url https://pypi.mandelblog.com/mandel/testing --extra-index-url https://pypi.mandelblog.com/mandel/stable dist/*.whl
          python -m pip check
          python -m pip install --index-url https://pypi.mandelblog.com/mandel/testing --extra-index-url https://pypi.mandelblog.com/mandel/stable responses freezegun empty_testproject ocyan.plugin.testing
          python -c 'import pathlib, ocyan, ocyan.plugin.ebay; assert any("site-packages" in str(p) for p in ocyan.__path__)'
          printf '%s\n' \
            'from empty_testproject.settings import *' \
            'from ocyan.main import settings as _ocyan_settings' \
            'from ocyan.plugin.oscar.settings import OSCAR_OCYAN_CONFIGURATION' \
            'from ocyan.plugin.oscar_checkout.settings import OCYAN_CHECKOUT_OSCAR_SETTINGS' \
            'globals().update(OSCAR_OCYAN_CONFIGURATION)' \
            'globals().update(OCYAN_CHECKOUT_OSCAR_SETTINGS)' \
            'OSCAR_ELASTICSEARCH_SERVER_URLS = ["http://127.0.0.1:9200"]' \
            'OSCAR_ELASTICSEARCH_ALLOW_INSECURE_HTTP = True' \
            'OSCAR_ELASTICSEARCH_VERIFY_CERTS = True' \
            'HAYSTACK_CONNECTIONS = {"default": {"ENGINE": "haystack.backends.simple_backend.SimpleEngine"}}' \
            'OSCAR_ADDRESS_HASH_FIELDS = ["salutation", "line1", "house_number", "line2", "line3", "line4", "postcode", "state", "country", "email"]' \
            'OSCAR_ADDRESS_BASE_FIELD_ORDER = []' \
            'OSCAR_ADDRESS_FORM_FIELD_ORDER = []' \
            'OSCAR_ADDRESS_FORM_FIELDS = ["email", "title", "first_name", "last_name", "line1", "house_number", "line2", "line3", "postcode", "state", "country", "phone_number"]' \
            'OCYAN_PARTNER_EU_VAT_RULES_ACTIVATED = True' \
            'OCYAN_PARTNER_RELATIVE_PRICE = True' \
            'EBAY_SANDBOX_ENABLED = True' \
            'EBAY_SITE_ID = "0"' \
            'EBAY_SELLERS_COUNTRY_CODE = "NL"' \
            'EBAY_SHIPPING_PROFILE_ID = "test-shipping"' \
            'EBAY_RETURN_PROFILE_ID = "test-return"' \
            'EBAY_IMG_DOMAIN = "example.invalid"' \
            'EBAY_ATTR_SYNC = "ebay_sync"' \
            'EBAY_ATTR_PRICE = "ebay_price"' \
            'EBAY_API_COMPATIBILITY_LEVEL = "1227"' \
            'INSTALLED_APPS = list(dict.fromkeys([x for x in list(getattr(_ocyan_settings, "INSTALLED_APPS", globals().get("INSTALLED_APPS", []))) if x.startswith("wagtail") or not (x.split(".")[-1] == "search" or x.endswith(".SearchConfig"))] + ["ocyan.plugin.oscar_catalogue", "ocyan.plugin.ebay"]))' \
            'WAGTAILADMIN_BASE_URL = "http://127.0.0.1:8000"' \
            'WAGTAILADMIN_STATIC_FILE_VERSION_STRINGS = False' \
            'STATIC_URL = "/static/"' \
            'MEDIA_URL = "/media/"' \
            'SECRET_KEY = "ci-only-not-for-production"' \
            'ROOT_URLCONF = "ci_urls"' \
            'STATIC_ROOT = "static"' \
            'COMPRESS_ROOT = STATIC_ROOT' \
            'DATABASES = {"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": "db.sqlite3"}}' \
            'MIGRATION_MODULES = {"catalogue": "ocyan.plugin.oscar_catalogue.oxyan_catalogue_extension.migrations", "order": "ocyan.plugin.oscar_order.oxyan_order_extension.migrations", "partner": "ocyan.plugin.oscar_partner.oxyan_partner_extension.migrations", "basket": "ocyan.plugin.oscar_basket.oxyan_basket_extension.migrations"}' \
            'MIDDLEWARE = ["django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware"]' \
            'TEMPLATES = [{"BACKEND": "django.template.backends.django.DjangoTemplates", "APP_DIRS": True, "OPTIONS": {"context_processors": ["django.template.context_processors.request", "django.contrib.auth.context_processors.auth", "django.contrib.messages.context_processors.messages"]}}]' > ci_settings.py
          printf '%s\n' 'urlpatterns = []' > ci_urls.py
          PYTHONPATH="$PWD" python -c 'import os,django; os.environ["DJANGO_SETTINGS_MODULE"]="ci_settings"; django.setup(); import oscar_elasticsearch.search.update as eu; eu.update_index_products=lambda *a, **k: None; import oscar_elasticsearch.search.signal_handlers as es; es.ProductElasticsearchIndex=type("DisabledIndex", (), {"delete": lambda self, *a, **k: None, "update_or_create": lambda self, *a, **k: None}); import ocyan.plugin.ebay.signal_handlers as s; s.update_index=es.update_index; from django.core.management import call_command; call_command("test", "ocyan/plugin/ebay/tests", verbosity=1)'
        '''
      }
    }
    stage('Sdist validation') {
      steps {
        sh '''#!/usr/bin/env bash
          set -euo pipefail
          python3.12 -m venv .venv-sdist
          . .venv-sdist/bin/activate
          python -m pip install --upgrade pip
          python -m pip install --index-url https://pypi.mandelblog.com/mandel/testing --extra-index-url https://pypi.mandelblog.com/mandel/stable dist/*.tar.gz
          python -m pip check
          python -m pip install --index-url https://pypi.mandelblog.com/mandel/testing --extra-index-url https://pypi.mandelblog.com/mandel/stable responses freezegun empty_testproject ocyan.plugin.testing
          python -c 'import ocyan, ocyan.plugin.ebay; assert any("site-packages" in str(p) for p in ocyan.__path__)'
          cp ci_settings.py ci_settings_sdist.py
          cp ci_urls.py ci_urls_sdist.py
          PYTHONPATH="$PWD" python -c 'import os,django; os.environ["DJANGO_SETTINGS_MODULE"]="ci_settings_sdist"; django.setup(); import oscar_elasticsearch.search.update as eu; eu.update_index_products=lambda *a, **k: None; import oscar_elasticsearch.search.signal_handlers as es; es.ProductElasticsearchIndex=type("DisabledIndex", (), {"delete": lambda self, *a, **k: None, "update_or_create": lambda self, *a, **k: None}); import ocyan.plugin.ebay.signal_handlers as s; s.update_index=es.update_index; from django.core.management import call_command; call_command("test", "ocyan/plugin/ebay/tests", verbosity=1)'
        '''
      }
    }
  }
  post { always { archiveArtifacts artifacts: 'dist/*', fingerprint: true } }
}
