name: CI/CD Pipeline

on:
  push:
    branches:
      - main
      - develop
      - 'feature/**'
      - 'bugfix/**'
      - 'hotfix/**'
      - 'release/**'
  pull_request:
    branches:
      - main
      - develop

jobs:
  validate:
    name: Validate Code Quality And Tests
    runs-on: ubuntu-latest
    container: xiaoxia-ci-python:3.12

    steps:
      - name: Checkout code
        run: |
          python - <<'PY'
          import os
          import tarfile
          import urllib.request

          api_url = os.environ['GITHUB_API_URL']
          repository = os.environ['GITHUB_REPOSITORY']
          sha = os.environ['GITHUB_SHA']
          token = os.environ.get('GITHUB_TOKEN', '')
          archive_url = f"{api_url}/repos/{repository}/archive/{sha}.tar.gz"
          request = urllib.request.Request(archive_url)
          if token:
              request.add_header('Authorization', f'token {token}')
          with urllib.request.urlopen(request, timeout=120) as response:
              with open('/tmp/repo.tar.gz', 'wb') as archive:
                  archive.write(response.read())
          with tarfile.open('/tmp/repo.tar.gz', 'r:gz') as archive:
              members = archive.getmembers()
              top_level = members[0].name.split('/')[0] + '/'
              for member in members:
                  member.name = member.name.removeprefix(top_level)
                  if member.name:
                      archive.extract(member, '.')
          PY

      - name: Verify CI environment
        run: |
          python --version
          python -m pip --version
          python -m black --version
          python -m isort --version-number
          python -m flake8 --version
          bandit --version
          pytest --version
          echo "✅ Prebuilt CI environment is ready"

      - name: Run code quality checks
        run: |
          python -m compileall -q alembic apps packages tests scripts
          python -m black --check alembic apps packages tests scripts
          python -m isort --check-only alembic apps packages tests scripts
          python -m flake8 apps packages tests --count --statistics

      - name: Run security scan
        run: |
          bandit -r apps packages -q

      - name: Validate release scripts syntax
        run: |
          bash -n scripts/backup_postgres.sh
          bash -n scripts/restore_postgres_plan.sh
          bash -n scripts/init_production_env.sh

      - name: Validate Alembic migrations
        run: |
          DATABASE_URL=postgresql+psycopg://postgres:postgres@localhost:5432/xiaoxia_saas \
            python -m alembic upgrade head --sql > /tmp/alembic-upgrade.sql
          test -s /tmp/alembic-upgrade.sql
          grep -q "Running upgrade" /tmp/alembic-upgrade.sql
          python scripts/check_schema_metadata.py

      - name: Run tests
        run: |
          python -m pytest tests -q

      - name: Build summary
        if: github.ref == 'refs/heads/develop' || github.ref == 'refs/heads/main'
        run: |
          echo "✅ Build completed successfully!"
          echo "Branch: ${GITHUB_REF_NAME}"
          echo "Commit: ${GITHUB_SHA}"
