import { tool } from "@opencode-ai/plugin"
import { runGh } from "./_shared"

const VERDICTS = ["APPROVE", "REQUEST_CHANGES", "NEEDS_DISCUSSION"] as const
type Verdict = typeof VERDICTS[number]

export default tool({
  description: "Post code review verdict as PR comment with deterministic heading. Reviewer agent uses this instead of raw `gh pr comment` to guarantee `## Code Review Summary` + `### Verdict: <verdict>` format that pipeline-status.py parses.",
  args: {
    pr_number: tool.schema.number().describe("PR number to comment on"),
    verdict: tool.schema.enum(VERDICTS).describe("Review verdict: APPROVE, REQUEST_CHANGES, or NEEDS_DISCUSSION"),
    body: tool.schema.string().describe("Review body text (without heading — heading is auto-generated)"),
    repo: tool.schema.string().optional().describe("Optional repo (owner/name). If omitted, gh auto-detects from context.worktree."),
  },
  async execute(args, context) {
    const comment = `## Code Review Summary\n\n${args.body}\n\n### Verdict: ${args.verdict}`
    const r = runGh(["pr", "comment", String(args.pr_number), "--body", comment], args.repo, { cwd: context.worktree })
    if (r.status !== 0) {
      return `⚠️ post-review failed for PR #${args.pr_number} (exit ${r.status}): ${r.stderr || r.stdout}`
    }
    return `Review posted on PR #${args.pr_number}: verdict=${args.verdict}`
  },
})