# Optional COSP GitHub Action (v0.1)
# Drop into .github/workflows/cosp.yml to mirror COSP Draft-PR claims onto issue labels/assignments.
# Repositories do NOT require this Action to use COSP; workers coordinate via Draft PRs regardless.

name: COSP Issue Claim Sync

on:
  pull_request_target:
    types: [opened, reopened, closed]

permissions:
  issues: write
  pull-requests: read

jobs:
  sync-cosp-claim:
    runs-on: ubuntu-latest
    steps:
      - name: Sync COSP claim status and reputation (Rule of 3)
        uses: actions/github-script@v7
        with:
          script: |
            const pr = context.payload.pull_request;
            const body = pr.body || "";
            const match = body.match(/<!--\s*cosp\s+([\s\S]*?)-->/);
            if (!match) {
              core.info("No COSP trailer found; skipping.");
              return;
            }

            const issueMatch = match[1].match(/issue:\s*(\d+)/);
            if (!issueMatch) {
              core.info("COSP trailer missing issue number; skipping.");
              return;
            }

            const issueNumber = Number(issueMatch[1]);
            const author = pr.user.login;
            const { owner, repo } = context.repo;
            const inProgressLabel = "in-progress";
            const contributorLabel = `cosp:${author}`;
            const trustedThreshold = 3; // Rule of 3 (configurable per repo)

            if (context.payload.action === "closed" && !pr.merged) {
              for (const label of [inProgressLabel, contributorLabel]) {
                try {
                  await github.rest.issues.removeLabel({ owner, repo, issue_number: issueNumber, name: label });
                } catch (_) {}
              }
              return;
            }

            if (context.payload.action === "opened" || context.payload.action === "reopened") {
              const q = `repo:${owner}/${repo} is:pr is:merged author:${author}`;
              const search = await github.rest.search.issuesAndPullRequests({ q, per_page: 1 });
              const mergedCount = search.data.total_count;

              const labelsToAdd = [inProgressLabel, contributorLabel];
              if (mergedCount >= trustedThreshold) {
                labelsToAdd.push("cosp:trusted");
              }

              await github.rest.issues.addLabels({
                owner,
                repo,
                issue_number: issueNumber,
                labels: labelsToAdd,
              });

              if (mergedCount >= trustedThreshold) {
                try {
                  await github.rest.issues.addAssignees({
                    owner,
                    repo,
                    issue_number: issueNumber,
                    assignees: [author],
                  });
                } catch (_) {
                  core.info(`Could not directly assign @${author} (external contributor); tracked via labels.`);
                }
              }
            }
