name: Tech Doc Writer

on:
  pull_request_target:
    types: [closed]

permissions:
  contents: write
  pull-requests: write
  issues: write

jobs:
  update-docs:
    runs-on: ubuntu-latest
    if: >-
      github.event.pull_request.merged == true &&
      !contains(github.event.pull_request.title, '[docs]') &&
      !contains(github.event.pull_request.title, 'chore(docs)')
    steps:
      - uses: actions/checkout@v4
        with:
          ref: main
          fetch-depth: 2

      - name: Gather diff context
        id: context
        run: |
          PR_TITLE="${{ github.event.pull_request.title }}"
          PR_NUM="${{ github.event.pull_request.number }}"

          CHANGED=$(git diff --name-only HEAD~1 HEAD)
          DIFF=$(git diff HEAD~1 HEAD -- ':(exclude)*.md' ':(exclude)*.yml' ':(exclude)*.json' ':(exclude).github/' ':(exclude)docs/' | head -500)
          SRC_CHANGES=$(echo "$CHANGED" | grep -vE '^\.(github|gitignore)|^(README|CHANGELOG|docs/|\.)|\.md$|\.yml$|\.json$' | head -1)

          if [ -z "$SRC_CHANGES" ]; then
            echo "skip=true" >> "$GITHUB_OUTPUT"
            exit 0
          fi

          echo "skip=false" >> "$GITHUB_OUTPUT"
          printf 'pr_title<<EOF\n%s\nEOF\n' "$PR_TITLE" >> "$GITHUB_OUTPUT"
          printf 'pr_num<<EOF\n%s\nEOF\n' "$PR_NUM" >> "$GITHUB_OUTPUT"
          echo "$CHANGED" > /tmp/changed_files.txt
          echo "$DIFF" > /tmp/code_diff.txt

      - name: Create doc update issue (unassigned)
        if: steps.context.outputs.skip != 'true'
        uses: actions/github-script@v7
        with:
          github-token: ${{ secrets.COPILOT_PAT }}
          script: |
            const fs = require('fs');
            const owner = context.repo.owner;
            const repo = context.repo.repo;
            const prNum = ${{ github.event.pull_request.number }};
            const prTitle = process.env.PR_TITLE || '';

            const changedFiles = fs.readFileSync('/tmp/changed_files.txt', 'utf8').trim();
            const codeDiff = fs.readFileSync('/tmp/code_diff.txt', 'utf8').trim();
        env:
          PR_TITLE: ${{ steps.context.outputs.pr_title }}

            // Dedup
            const existing = await github.rest.issues.listForRepo({
              owner, repo, state: 'open', labels: 'documentation', per_page: 20
            });
            if (existing.data.some(i => i.title.includes(`PR #${prNum}`))) return;

            const body = `## Documentation Update Required

> ⚠️ **Do NOT assume existing docs are correct.** Verify all doc claims against the actual source code. Use \`git diff HEAD~1 HEAD\` as your source of truth.

PR #${prNum} (\`${prTitle}\`) merged code changes.

### Changed Files
\`\`\`
${changedFiles}
\`\`\`

### Code Diff (truncated)
\`\`\`diff
${codeDiff.substring(0, 3000)}
\`\`\`

### Tasks
- [ ] Review the diff and identify public API/behavior/config changes
- [ ] Update README.md if usage changed
- [ ] Update or create relevant docs/ files
- [ ] Update CHANGELOG.md
- [ ] Verify code examples against current source

---
_Auto-generated by Tech Doc Writer (ADR-0005)_`;

            const issue = await github.rest.issues.create({
              owner, repo,
              title: `[docs] Update documentation for PR #${prNum}: ${prTitle}`,
              body,
              labels: ['documentation']
            });

            try {
              await github.request('PATCH /repos/{owner}/{repo}/issues/{issue_number}', {
                owner, repo, issue_number: issue.data.number, type: 'Task'
              });
            } catch (e) {}

            // Do NOT assign Copilot here — queue-advance handles assignment
            // to prevent race condition with simultaneous feature assignment
            console.log(`📝 Created doc issue #${issue.data.number} (unassigned, queue-advance will pick up)`);
