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

export default tool({
  description: "Merge a PR via squash + delete branch. Orchestrator-safe wrapper for `gh pr merge N --squash --delete-branch`. Main agent calls this tool instead of raw bash, aligning with the pure-orchestrator model (tool-led philosophy, see ADR-010).",
  args: {
    pr_number: tool.schema.number().describe("PR number to merge"),
    repo: tool.schema.string().optional().describe("Optional repo (owner/name). If omitted, gh auto-detects from context.worktree."),
  },
  async execute(args, context) {
    const r = runGh(
      ["pr", "merge", String(args.pr_number), "--squash", "--delete-branch"],
      args.repo,
      { cwd: context.worktree },
    )

    if (r.status !== 0) {
      return `⚠️ merge_pr failed for PR #${args.pr_number} (exit ${r.status}): ${r.stderr || r.stdout}`
    }

    return `PR #${args.pr_number} merged successfully (squash, branch deleted).`
  },
})