name: Model Page Discovery

on:
  schedule:
    - cron: '0 9 * * 1'
  workflow_dispatch:

jobs:
  discover:
    runs-on: ubuntu-latest
    permissions:
      contents: read
      issues: write

    steps:
      - name: Fetch model labels from hub API
        id: hub
        shell: bash
        run: |
          set -euo pipefail
          curl -fsSL 'https://comfy.org/api/hub/labels?type=model' -o hub-labels.json
          echo "Fetched $(jq '.labels | length' hub-labels.json) model labels from hub"

      - name: Checkout ComfyUI_frontend
        uses: actions/checkout@v6
        with:
          sparse-checkout: apps/website/src/config/generated-models.json

      - name: Compare against existing models
        id: compare
        shell: bash
        run: |
          set -euo pipefail

          HUB_SLUGS=$(jq -r '[.labels[].name]' hub-labels.json)

          EXISTING_SLUGS=$(node -e "
            const fs = require('fs');
            const models = JSON.parse(
              fs.readFileSync(
                'apps/website/src/config/generated-models.json',
                'utf8'
              )
            );
            console.log(JSON.stringify(models.map(m => m.slug)));
          " 2>/dev/null || echo '[]')

          ADDED_SLUGS=$(node -e "
            const hub = $HUB_SLUGS;
            const existing = new Set($EXISTING_SLUGS);
            console.log(JSON.stringify(hub.filter(s => !existing.has(s))));
          ")

          COUNT=$(node -e "console.log($ADDED_SLUGS.length)")
          echo "new_count=$COUNT" >> \$GITHUB_OUTPUT
          echo "new_slugs=$ADDED_SLUGS" >> \$GITHUB_OUTPUT

          if [ "\$COUNT" -eq 0 ]; then
            echo "No new models found."
          else
            echo "Found \$COUNT new model(s)"
          fi

      - name: Check for existing open discovery issue
        id: existing_issue
        if: steps.compare.outputs.new_count != '0'
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        shell: bash
        run: |
          COUNT=$(gh issue list \
            --repo "$GITHUB_REPOSITORY" \
            --state open \
            --search 'in:title "New models detected"' \
            --json number \
            --jq 'length')
          echo "open_count=$COUNT" >> $GITHUB_OUTPUT

      - name: Open GitHub issue for new models
        if: |
          steps.compare.outputs.new_count != '0' &&
          steps.existing_issue.outputs.open_count == '0'
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          NEW_SLUGS: ${{ steps.compare.outputs.new_slugs }}
          NEW_COUNT: ${{ steps.compare.outputs.new_count }}
        shell: bash
        run: |
          SLUG_LIST=$(node -e "
            const slugs = $NEW_SLUGS;
            console.log(slugs.map(s => '- \`' + s + '\`').join('\n'));
          ")

          gh issue create \
            --repo "$GITHUB_REPOSITORY" \
            --title "New models detected — add to model pages" \
            --body "## $NEW_COUNT new model(s) found in hub

          The weekly model discovery scan found model labels on the hub not yet in
          \`apps/website/src/config/generated-models.json\`.

          ### New slugs ($NEW_COUNT)

          $SLUG_LIST

          ### Next steps

          1. Review which of these warrant an SEO model page
          2. For local models: run \`SKIP_THUMBNAILS=1 pnpm generate:models\` and commit the result
          3. For partner/API models: add to \`API_PROVIDER_MAP\` in \`generate-models.ts\`, regenerate, commit

          ---
          *Generated by the [model-page-discovery workflow](https://github.com/$GITHUB_REPOSITORY/actions/workflows/model-page-discovery.yaml)*"

      - name: Skip — open issue already exists
        if: |
          steps.compare.outputs.new_count != '0' &&
          steps.existing_issue.outputs.open_count != '0'
        run: echo "An open discovery issue already exists — skipping creation."

      - name: No new models found
        if: steps.compare.outputs.new_count == '0'
        run: echo "No new models found — nothing to do."
