// SPEC: PJ2026-010606 GitHub入口 draft-2026-06-25-gh-split
// Moved mechanically from scripts/src/gh.ts:5682-5947.

import path from "node:path";
import { bodySafetySignals, bodySha, preview, repoParts } from "./auth-and-safety";
import { readMarkdownBody, readOptionalMarkdownBody } from "./body-input";
import { commandError, githubRequest, isGitHubError, validationError } from "./client";
import { isRecord } from "./notify-claudeqq";
import { prSummary } from "./pr-summary";
import { commentSummary, ghShort, ghTable, ghText } from "./render";
import { branchInfo, branchSummary, compareBranches, compareSummary, prCommentPlannedOperation, prCreatePlannedOperation, prUrl, repoInfo, repoSummary } from "./repo-compare";
import type { BodyUpdateMode, GitHubCommandResult, GitHubComment, GitHubOptions, GitHubPullRequest } from "./types";

function prCreateNext(repo: string, number: string, status: "created" | "dry-run", draft: boolean): Record<string, unknown> {
  const target = status === "created" && number !== "-" ? number : "<pr-number>";
  return {
    policy: "bounded-pr-create-next",
    defaultState: draft ? "waiting-ready-for-review" : "waiting-pr-monitor",
    states: {
      "waiting-pr-monitor": "PR 已创建；默认等待自动 PR monitor 或主代理按 $unidesk-subagent 执行受控 review/preflight/merge。",
      "review-or-check-blocker": "review、mergeability 或 check 未满足时只做有界 review/preflight/status 下钻。",
      "automatic-delivery-anomaly": "合并后的自动链异常只做只读 status/history 诊断，修 owning YAML/controller/source，不手工补 CI/CD。",
    },
    commands: {
      observe: `bun scripts/cli.ts gh pr view ${target} --repo ${repo}`,
      review: `bun scripts/cli.ts gh pr review-plan ${target} --repo ${repo}`,
      preflight: `bun scripts/cli.ts gh pr preflight ${target} --repo ${repo}`,
      status: `bun scripts/cli.ts gh pr view ${target} --repo ${repo} --json headRefName,baseRefName,mergeable,mergeStateStatus,statusCheckRollup`,
      ...(draft ? { ready: `bun scripts/cli.ts gh pr ready ${target} --repo ${repo}` } : {}),
      ...(status === "dry-run" ? { create: "rerun without --dry-run to create the PR" } : {}),
    },
    suppressedDefaults: ["gh pr merge", "preflight --full", "preflight --raw", "manual CI/CD", "mirror sync", "PipelineRun", "Argo refresh"],
  };
}

export function prEditBodyPlan(mode: BodyUpdateMode, input: { body: string; bodySource: Record<string, unknown> } | null, finalBody: string | undefined, existingBody: string | null): Record<string, unknown> | null {
  if (input === null || finalBody === undefined) return null;
  return {
    mode,
    bodySource: input.bodySource,
    input: bodySafetySignals(input.body),
    existingBody: existingBody === null ? { fetched: false } : { fetched: true, bodyChars: existingBody.length, bodySha: bodySha(existingBody) },
    finalBody: bodySafetySignals(finalBody),
  };
}

export async function prCreate(repo: string, token: string, options: GitHubOptions): Promise<GitHubCommandResult> {
  if (options.title === undefined) return validationError("pr create", repo, "pr create requires --title <title>");
  if (options.base === undefined) return validationError("pr create", repo, "pr create requires --base <branch>");
  if (options.head === undefined) return validationError("pr create", repo, "pr create requires --head <branch>");
  let bodySource: { body: string; bodySource: Record<string, unknown> };
  try {
    bodySource = readMarkdownBody(options, "pr create");
  } catch (error) {
    return validationError("pr create", repo, error instanceof Error ? error.message : String(error));
  }
  const body = bodySource.body;
  const planned = prCreatePlannedOperation(repo, options, body, bodySource.bodySource);
  if (options.dryRun) {
    return withPrCreateRendered({
      ok: true,
      command: "pr create",
      repo,
      dryRun: true,
      planned: true,
      draft: options.draft,
      next: prCreateNext(repo, "<pr-number>", "dry-run", options.draft),
      ...planned,
    });
  }

  const repoResult = await repoInfo(token, repo);
  if (isGitHubError(repoResult)) return commandError("pr create", repo, repoResult, { planned });
  const baseBranch = await branchInfo(token, repo, options.base);
  if (isGitHubError(baseBranch)) return commandError("pr create", repo, baseBranch, { base: options.base, planned });
  const headBranch = await branchInfo(token, repo, options.head);
  if (isGitHubError(headBranch)) return commandError("pr create", repo, headBranch, { head: options.head, planned });
  const compare = await compareBranches(token, repo, options.base, options.head);
  if (isGitHubError(compare)) return commandError("pr create", repo, compare, { base: options.base, head: options.head, planned });
  const aheadBy = typeof compare.ahead_by === "number" ? compare.ahead_by : null;
  if (aheadBy === null || aheadBy <= 0) {
    return validationError("pr create", repo, "head branch must be ahead of base branch before creating a PR", {
      base: options.base,
      head: options.head,
      compare: compareSummary(compare),
    });
  }

  const { owner, name } = repoParts(repo);
  const payload: Record<string, unknown> = {
    title: options.title,
    base: options.base,
    head: options.head,
    draft: options.draft,
    body,
  };
  const pr = await githubRequest<GitHubPullRequest>(token, "POST", `/repos/${owner}/${name}/pulls`, payload);
  if (isGitHubError(pr)) return commandError("pr create", repo, pr, { base: options.base, head: options.head, planned });
  return withPrCreateRendered({
    ok: true,
    command: "pr create",
    repo,
    pr: prSummary(pr),
    validation: {
      repo: repoSummary(repoResult),
      base: branchSummary(baseBranch),
      head: branchSummary(headBranch),
      compare: compareSummary(compare),
      bodySource: bodySource.bodySource,
    },
    request: {
      method: "POST",
      path: `/repos/${owner}/${name}/pulls`,
      title: options.title,
      base: options.base,
      head: options.head,
      draft: options.draft,
      bodyChars: body.length,
    },
    next: prCreateNext(repo, String(pr.number), "created", pr.draft === true),
    rest: true,
  });
}

export function withPrCreateRendered(result: GitHubCommandResult): GitHubCommandResult {
  return {
    ...result,
    contentType: "text/plain",
    renderedText: renderPrCreateTable(result),
  };
}

export function renderPrCreateTable(result: GitHubCommandResult): string {
  const pr = isRecord(result.pr) ? result.pr : {};
  const request = isRecord(result.request) ? result.request : {};
  const number = ghText(pr.number ?? result.number ?? result.pr);
  const title = ghText(pr.title ?? request.title ?? result.title);
  const base = ghText(isRecord(pr.base) ? pr.base.ref : request.base ?? result.base);
  const head = ghText(isRecord(pr.head) ? pr.head.ref : request.head ?? result.head);
  const draft = request.draft === true || pr.draft === true || result.draft === true;
  const status = result.dryRun === true ? "dry-run" : "created";
  const next = isRecord(result.next) ? result.next : prCreateNext(ghText(result.repo), number === "-" ? "<pr-number>" : number, status, draft);
  const commands = isRecord(next.commands) ? next.commands : {};
  const rows = [[
    number === "-" ? "-" : `#${number}`,
    status,
    base,
    head,
    ghText(draft),
    ghShort(title, 80),
  ]];
  const lines = [
    `gh pr create (${status})`,
    "",
    ghTable(["PR", "STATUS", "BASE", "HEAD", "DRAFT", "TITLE"], rows),
    "",
    "Summary:",
    `  repo=${ghText(result.repo)} url=${ghText(pr.url ?? pr.html_url ?? result.url)}`,
    `  nextState=${ghText(next.defaultState)} policy=${ghText(next.policy)}`,
    "",
    "Next:",
  ];
  if (typeof commands.create === "string") lines.push(`  ${commands.create}`);
  if (typeof commands.ready === "string") lines.push(`  ${commands.ready}`);
  for (const key of ["observe", "review", "preflight", "status"]) {
    if (typeof commands[key] === "string") lines.push(`  ${key}: ${commands[key]}`);
  }
  lines.push("  flow: main agent follows $unidesk-subagent review/preflight/merge policy; do not use full/raw disclosure or manual delivery repair by default.");
  lines.push("", "Disclosure:");
  lines.push("  default view is bounded; --full/--raw and manual merge/delivery commands require explicit disclosure or merge authorization.");
  return lines.join("\n");
}

export async function prComment(repo: string, token: string, issueNumber: number, options: GitHubOptions): Promise<GitHubCommandResult> {
  let bodySource: { body: string; bodySource: Record<string, unknown> };
  try {
    bodySource = readMarkdownBody(options, "pr comment");
  } catch (error) {
    return validationError("pr comment", repo, error instanceof Error ? error.message : String(error), { issueNumber });
  }
  const body = bodySource.body;
  const planned = prCommentPlannedOperation(repo, issueNumber, body, bodySource.bodySource);
  if (options.dryRun) {
    return {
      ok: true,
      command: "pr comment",
      repo,
      dryRun: true,
      planned: true,
      issueNumber,
      ...planned,
    };
  }

  const repoResult = await repoInfo(token, repo);
  if (isGitHubError(repoResult)) return commandError("pr comment", repo, repoResult, { issueNumber, planned });
  const { owner, name } = repoParts(repo);
  const prResult = await githubRequest<GitHubPullRequest>(token, "GET", `/repos/${owner}/${name}/pulls/${issueNumber}`);
  if (isGitHubError(prResult)) return commandError("pr comment", repo, prResult, { issueNumber, planned });
    const comment = await githubRequest<GitHubComment>(token, "POST", `/repos/${owner}/${name}/issues/${issueNumber}/comments`, { body });
    if (isGitHubError(comment)) return commandError("pr comment", repo, comment, { issueNumber, planned });
    return {
      ok: true,
      command: "pr comment create",
    repo,
    issueNumber,
    pr: prSummary(prResult),
    comment: commentSummary(comment),
    bodySource: bodySource.bodySource,
    source: String(bodySource.bodySource.kind ?? "unknown"),
    bodyChars: body.length,
    bodySha: bodySha(body),
    bodyPreview: preview(body),
    request: {
      method: "POST",
      path: `/repos/${owner}/${name}/issues/${issueNumber}/comments`,
      bodyChars: body.length,
    },
    validation: {
      repo: repoSummary(repoResult),
      pr: prSummary(prResult),
      bodySource: bodySource.bodySource,
    },
    rest: true,
  };
}

export async function prUpdate(repo: string, token: string, number: number, options: GitHubOptions, commandName = "pr update"): Promise<GitHubCommandResult> {
  let bodySource: { body: string; bodySource: Record<string, unknown> } | null;
  try {
    bodySource = readOptionalMarkdownBody(options, commandName);
  } catch (error) {
    return validationError(commandName, repo, error instanceof Error ? error.message : String(error), { number });
  }
  if (bodySource === null && options.title === undefined) {
    return validationError(commandName, repo, `${commandName} requires --title <title>, --body-stdin, --body-file <file|->, or --body <text>`, { number });
  }
  if (options.mode === "append" && bodySource === null) {
    return validationError(commandName, repo, `${commandName} --mode append requires a body source`, { number });
  }
  const { owner, name } = repoParts(repo);
  let oldPr: GitHubPullRequest | null = null;
  if (token.length > 0 && options.mode === "append") {
    const pr = await githubRequest<GitHubPullRequest>(token, "GET", `/repos/${owner}/${name}/pulls/${number}`);
    if (isGitHubError(pr)) return commandError(commandName, repo, pr, { number, phase: "read-before-update" });
    oldPr = pr;
  }
  const finalBody = bodySource === null ? undefined : (options.mode === "append" ? `${oldPr?.body ?? ""}${bodySource.body}` : bodySource.body);
  const changedFields = [
    ...(options.title === undefined ? [] : ["title"]),
    ...(bodySource === null ? [] : ["body"]),
  ];
  const bodyPlan = prEditBodyPlan(options.mode, bodySource, finalBody, oldPr?.body ?? null);
  const request = {
    method: "PATCH",
    path: `/repos/{owner}/{repo}/pulls/${number}`,
    changedFields,
    body: {
      ...(options.title === undefined ? {} : { title: "provided" }),
      ...(finalBody === undefined ? {} : { bodyChars: finalBody.length, bodySha: bodySha(finalBody) }),
    },
  };
  if (options.dryRun) {
    return {
      ok: true,
      command: commandName,
      repo,
      dryRun: true,
      planned: true,
      number,
      url: prUrl(repo, number),
      changedFields,
      ...(bodyPlan === null ? {} : { body: bodyPlan }),
      request,
      graphQl: false,
      projectsClassic: false,
    };
  }
  const payload: Record<string, unknown> = {};
  if (finalBody !== undefined) payload.body = finalBody;
  if (options.title !== undefined) payload.title = options.title;
  const pr = await githubRequest<GitHubPullRequest>(token, "PATCH", `/repos/${owner}/${name}/pulls/${number}`, payload);
  if (isGitHubError(pr)) return commandError(commandName, repo, pr, { number, planned: { changedFields, body: bodyPlan, request } });
  return {
    ok: true,
    command: commandName,
    repo,
    pr: pr.number ?? number,
    number: pr.number ?? number,
    changedFields,
    url: pr.html_url ?? prUrl(repo, number),
    ...(bodyPlan === null ? {} : { body: bodyPlan }),
    request: { ...request, path: `/repos/${owner}/${name}/pulls/${number}` },
    rest: true,
    graphQl: false,
    projectsClassic: false,
  };
}

export async function prState(repo: string, token: string, number: number, state: "open" | "closed", dryRun: boolean): Promise<GitHubCommandResult> {
  const command = state === "closed" ? "pr close" : "pr reopen";
  if (dryRun) return { ok: true, command, repo, dryRun: true, number, wouldPatch: { state } };
  const { owner, name } = repoParts(repo);
  const pr = await githubRequest<GitHubPullRequest>(token, "PATCH", `/repos/${owner}/${name}/pulls/${number}`, { state });
  if (isGitHubError(pr)) return commandError(command, repo, pr, { number });
  return { ok: true, command, repo, number, pullRequest: prSummary(pr), rest: true };
}
