name: Metatopia GWI Visual & Security PR Gate
on:
  pull_request:
    types: [opened, synchronize, reopened]

jobs:
  gwi-visual-gate:
    runs-on: ubuntu-latest
    permissions:
      contents: read
      pull-requests: write
    steps:
      - name: Run Sovereign GWI v1.4.0 Visual & Security PR Gate
        id: gwi_gate
        env:
          METATOPIA_API_KEY: ${{ secrets.METATOPIA_API_KEY }}
          PR_TARGET_URL: ${{ github.event.pull_request.html_url }}
          REPO_SLUG: ${{ github.repository }}
          PR_NUMBER: ${{ github.event.pull_request.number }}
        run: |
          curl -sS -X POST "https://templates.metatopia.gr/api/pr-gate/evaluate" \
            -H "Content-Type: application/json" \
            -H "Authorization: Bearer ${METATOPIA_API_KEY}" \
            -d "{\"targetUrl\":\"${PR_TARGET_URL}\",\"repoSlug\":\"${REPO_SLUG}\",\"prNumber\":${PR_NUMBER}}" \
            > gwi-gate-result.json
          jq -r '.prCommentMarkdown' gwi-gate-result.json > pr-comment.md
          cat pr-comment.md

      - name: Post GWI Visual Gate Report on Pull Request
        if: always()
        uses: actions/github-script@v7
        with:
          script: |
            const fs = require('fs');
            const body = fs.readFileSync('pr-comment.md', 'utf8');
            await github.rest.issues.createComment({
              owner: context.repo.owner,
              repo: context.repo.repo,
              issue_number: context.issue.number,
              body
            });
