name: Build WebKit Filters

on:
  schedule:
    - cron: '0 18 * * *'
  workflow_dispatch:

permissions:
  contents: read

concurrency:
  group: webkit-filter-publish
  cancel-in-progress: false

jobs:
  build:
    runs-on: macos-latest
    timeout-minutes: 30

    steps:
      - name: Checkout repository
        uses: actions/checkout@v4

      - name: Check deployment configuration
        if: github.ref == 'refs/heads/main'
        env:
          CF_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
          CF_ACCOUNT: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
          CF_PROJECT: ${{ vars.CLOUDFLARE_PAGES_PROJECT }}
        run: |
          set -euo pipefail
          test -n "$CF_TOKEN" || { echo "::error::CLOUDFLARE_API_TOKEN is missing"; exit 1; }
          test -n "$CF_ACCOUNT" || { echo "::error::CLOUDFLARE_ACCOUNT_ID is missing"; exit 1; }
          test "$CF_PROJECT" = "webkit-adblock-filters" || { echo "::error::CLOUDFLARE_PAGES_PROJECT must be webkit-adblock-filters"; exit 1; }

      - name: Download 5 Filters and Convert to WebKit JSON
        run: |
          set -euo pipefail
          mkdir -p dist/source
          rm -f combined_filter.txt

          # 採用した5本のフィルタID (ベース, モバイル広告, 日本語, 追跡防止, アプリバナー)
          FILTER_IDS=(2 11 7 3 20)

          echo "1. 5本のフィルタをダウンロードして結合中..."
          for id in "${FILTER_IDS[@]}"; do
            url="https://filters.adtidy.org/ios/filters/${id}_optimized.txt"
            echo "Fetching Filter ID: ${id} (${url})"
            file="dist/source/${id}_optimized.txt"
            curl --fail --silent --show-error --location \
              --retry 3 --connect-timeout 15 --max-time 120 \
              "$url" -o "$file"
            test -s "$file"
            if ! grep -Eq '^![[:space:]]*Title:' "$file"; then
              echo "::error::Invalid filter header: ${id}"
              exit 1
            fi
            cat "$file" >> combined_filter.txt
            echo "" >> combined_filter.txt
          done

          echo "結合後の総行数: $(wc -l < combined_filter.txt) 行"

          echo "2. AdGuard公式 SafariConverterLib CLI のビルド..."
          git clone --depth 1 https://github.com/AdguardTeam/SafariConverterLib.git
          git -C SafariConverterLib rev-parse HEAD > dist/source/converter-commit.txt
          cd SafariConverterLib
          swift build -c release --product ConverterTool

          echo "3. WebKit用JSONへ変換中..."
          .build/release/ConverterTool convert \
            --safari-version 26 \
            --input-path ../combined_filter.txt \
            --safari-rules-json-path ../dist/rules_raw.json

          cd ..

          echo "4. JSONを1行にMinify（軽量化）して集計..."
          jq -e '
            type == "array" and length > 0 and length <= 150000 and
            all(.[];
              (.trigger | type == "object") and
              (.action | type == "object") and
              (.trigger["url-filter"] | type == "string") and
              (.action.type | type == "string")
            )
          ' dist/rules_raw.json > /dev/null
          jq -c '.' dist/rules_raw.json > dist/rules.json
          rm dist/rules_raw.json

          # 変換後のルール数をログに出力（WebKit上限15万ルールの確認用）
          RULE_COUNT=$(jq 'length' dist/rules.json)
          echo "=========================================="
          echo "変換完了！ 総ルール数: ${RULE_COUNT} / 150,000"
          echo "=========================================="

          test -s LICENSE
          cp LICENSE dist/LICENSE.txt
          cp .github/workflows/update-filters.yml dist/source/update-filters.yml
          cp distribution/NOTICE.txt dist/NOTICE.txt
          cp distribution/_headers dist/_headers
          cp distribution/index.html dist/index.html
          shasum -a 256 dist/rules.json > dist/rules.sha256
          date -u +"%Y-%m-%dT%H:%M:%SZ" > dist/version.txt

          ls -lh dist/

      - name: Upload Artifact for testing
        uses: actions/upload-artifact@v4
        with:
          name: webkit-filter-dist
          path: dist/
          retention-days: 5
          if-no-files-found: error

      - name: Deploy filters to Cloudflare Pages
        if: github.ref == 'refs/heads/main'
        uses: cloudflare/wrangler-action@v4
        with:
          apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
          accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
          wranglerVersion: '4.151.1'
          command: pages deploy dist --project-name=${{ vars.CLOUDFLARE_PAGES_PROJECT }} --branch=main
