name: Create Release Package

on:
  push:
    tags:
      - 'v*'

jobs:
  build-release:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout code with submodules
        uses: actions/checkout@v4
        with:
          submodules: recursive
          fetch-depth: 0

      - name: Setup PHP
        uses: shivammathur/setup-php@v2
        with:
          php-version: '8.3'
          extensions: mbstring, xml, zip, intl, gettext
          tools: composer:v2

      - name: Extract version from tag
        id: version
        run: |
          VERSION=${GITHUB_REF#refs/tags/v}
          echo "version=$VERSION" >> $GITHUB_OUTPUT
          echo "Building version: $VERSION"

      - name: Validate composer.json
        run: composer validate --strict

      - name: Install dependencies
        run: composer install --no-dev --optimize-autoloader --prefer-dist

      - name: Install gettext for translation compilation
        run: sudo apt-get update && sudo apt-get install -y gettext

      - name: Compile translations
        run: |
          for po in languages/*.po; do
            if [ -f "$po" ]; then
              mo="${po%.po}.mo"
              echo "Compiling $po -> $mo"
              msgfmt -o "$mo" "$po"
            fi
          done

      - name: Verify version in plugin header
        run: |
          PLUGIN_VERSION=$(grep -oP 'Version:\s*\K[0-9]+\.[0-9]+\.[0-9]+' wc-licensed-product.php | head -1)
          TAG_VERSION=${{ steps.version.outputs.version }}
          if [ "$PLUGIN_VERSION" != "$TAG_VERSION" ]; then
            echo "Version mismatch! Plugin header: $PLUGIN_VERSION, Tag: $TAG_VERSION"
            exit 1
          fi
          echo "Version verified: $PLUGIN_VERSION"

      - name: Create release directory
        run: mkdir -p releases

      - name: Build release package
        run: |
          PLUGIN_NAME="wc-licensed-product"
          VERSION=${{ steps.version.outputs.version }}
          RELEASE_FILE="releases/${PLUGIN_NAME}-${VERSION}.zip"

          # Create zip from parent directory to maintain proper subdirectory structure
          cd ..
          zip -r "${PLUGIN_NAME}/${RELEASE_FILE}" "${PLUGIN_NAME}" \
            -x "${PLUGIN_NAME}/.git/*" \
            -x "${PLUGIN_NAME}/.gitea/*" \
            -x "${PLUGIN_NAME}/.gitmodules" \
            -x "${PLUGIN_NAME}/.gitignore" \
            -x "${PLUGIN_NAME}/lib/*" \
            -x "${PLUGIN_NAME}/releases/*" \
            -x "${PLUGIN_NAME}/vendor/magdev/wc-licensed-product-client/.git" \
            -x "${PLUGIN_NAME}/vendor/magdev/wc-licensed-product-client/.git/*" \
            -x "${PLUGIN_NAME}/vendor/*/.git/*" \
            -x "${PLUGIN_NAME}/tests/*" \
            -x "${PLUGIN_NAME}/CLAUDE.md" \
            -x "${PLUGIN_NAME}/*.po~" \
            -x "${PLUGIN_NAME}/wp-core" \
            -x "${PLUGIN_NAME}/wp-plugins" \
            -x "${PLUGIN_NAME}/composer.lock"

          echo "Created release package: ${RELEASE_FILE}"

      - name: Generate SHA256 checksum
        run: |
          VERSION=${{ steps.version.outputs.version }}
          cd releases
          sha256sum "wc-licensed-product-${VERSION}.zip" > "wc-licensed-product-${VERSION}.zip.sha256"
          cat "wc-licensed-product-${VERSION}.zip.sha256"

      - name: Verify package structure
        run: |
          VERSION=${{ steps.version.outputs.version }}
          echo "=== Package contents ==="
          unzip -l "releases/wc-licensed-product-${VERSION}.zip" | head -50

          echo ""
          echo "=== Verification checks ==="

          # Check main plugin file exists
          if unzip -l "releases/wc-licensed-product-${VERSION}.zip" | grep -q "wc-licensed-product/wc-licensed-product.php"; then
            echo "Main plugin file: OK"
          else
            echo "ERROR: Main plugin file not found!"
            exit 1
          fi

          # Check vendor directory exists
          if unzip -l "releases/wc-licensed-product-${VERSION}.zip" | grep -q "wc-licensed-product/vendor/"; then
            echo "Vendor directory: OK"
          else
            echo "ERROR: Vendor directory not found!"
            exit 1
          fi

          # Check lib directory is excluded
          if unzip -l "releases/wc-licensed-product-${VERSION}.zip" | grep -q "wc-licensed-product/lib/"; then
            echo "ERROR: lib/ directory should be excluded!"
            exit 1
          else
            echo "lib/ excluded: OK"
          fi

          # Check .git directories are excluded
          if unzip -l "releases/wc-licensed-product-${VERSION}.zip" | grep -q "\.git"; then
            echo "WARNING: .git files found in package"
          else
            echo ".git excluded: OK"
          fi

      - name: Extract changelog for release
        id: changelog
        run: |
          VERSION=${{ steps.version.outputs.version }}
          # Extract changelog section for this version
          CHANGELOG=$(awk "/^## \[?${VERSION}\]?/,/^## \[?[0-9]+\.[0-9]+\.[0-9]+\]?/" CHANGELOG.md | head -n -1)
          if [ -z "$CHANGELOG" ]; then
            CHANGELOG="Release v${VERSION}"
          fi
          # Escape for GitHub Actions
          echo "changelog<<EOF" >> $GITHUB_OUTPUT
          echo "$CHANGELOG" >> $GITHUB_OUTPUT
          echo "EOF" >> $GITHUB_OUTPUT

      - name: Create Gitea Release
        id: create_release
        run: |
          VERSION=${{ steps.version.outputs.version }}
          TAG_NAME=${{ github.ref_name }}

          # Determine if prerelease
          if [[ "$TAG_NAME" == *"-"* ]]; then
            PRERELEASE=true
          else
            PRERELEASE=false
          fi

          # Escape changelog for JSON
          CHANGELOG_ESCAPED=$(echo '${{ steps.changelog.outputs.changelog }}' | jq -Rs .)

          # Create release via Gitea API
          RESPONSE=$(curl -s -X POST \
            -H "Authorization: token ${{ secrets.SRC_GITEA_TOKEN }}" \
            -H "Content-Type: application/json" \
            "${GITHUB_SERVER_URL}/api/v1/repos/${GITHUB_REPOSITORY}/releases" \
            -d "{
              \"tag_name\": \"${TAG_NAME}\",
              \"name\": \"v${VERSION}\",
              \"body\": ${CHANGELOG_ESCAPED},
              \"draft\": false,
              \"prerelease\": ${PRERELEASE}
            }")

          # Extract release ID
          RELEASE_ID=$(echo "$RESPONSE" | jq -r '.id')
          echo "Release ID: $RELEASE_ID"
          echo "release_id=$RELEASE_ID" >> $GITHUB_OUTPUT

          if [ "$RELEASE_ID" == "null" ] || [ -z "$RELEASE_ID" ]; then
            echo "Failed to create release"
            echo "$RESPONSE"
            exit 1
          fi

      - name: Upload Release Assets
        run: |
          VERSION=${{ steps.version.outputs.version }}
          RELEASE_ID=${{ steps.create_release.outputs.release_id }}

          # Upload zip file
          curl -s -X POST \
            -H "Authorization: token ${{ secrets.SRC_GITEA_TOKEN }}" \
            -H "Content-Type: application/octet-stream" \
            "${GITHUB_SERVER_URL}/api/v1/repos/${GITHUB_REPOSITORY}/releases/${RELEASE_ID}/assets?name=wc-licensed-product-${VERSION}.zip" \
            --data-binary @"releases/wc-licensed-product-${VERSION}.zip"

          # Upload checksum file
          curl -s -X POST \
            -H "Authorization: token ${{ secrets.SRC_GITEA_TOKEN }}" \
            -H "Content-Type: application/octet-stream" \
            "${GITHUB_SERVER_URL}/api/v1/repos/${GITHUB_REPOSITORY}/releases/${RELEASE_ID}/assets?name=wc-licensed-product-${VERSION}.zip.sha256" \
            --data-binary @"releases/wc-licensed-product-${VERSION}.zip.sha256"

          echo "Assets uploaded successfully"
