// SPEC: PJ2026-01060703 CI/CD branch follower and GH-1548/GH-1560 Gitea PaC migration.
// Responsibility: thin CI/CD top-level route entry; subcommand logic lives in responsibility modules.
import type { UniDeskConfig } from "./config";
import { renderMachine } from "./cicd-render";
import type { RenderedCliResult } from "./output";
import { cicdHelp as branchFollowerHelp, runCicdCommand as runBranchFollowerCommand } from "./cicd-branch-follower";
import { cicdGiteaActionsPocHelp, runGiteaActionsPocCommand } from "./cicd-gitea-actions-poc";
import { cicdNodeStatusHelp, runCicdNodeStatusCommand } from "./cicd-node-status";

export function cicdHelp(): unknown {
  return {
    command: "cicd status|gitea-actions-poc|branch-follower",
    output: "text by default for subcommands; top-level help is json",
    nodeStatus: {
      primary: "bun scripts/cli.ts cicd status --node NC01",
      note: "用于只读汇总节点上的 AgentRun、HWLAB、Web sentinel 与 unidesk-host PaC consumer。",
    },
    migration: {
      issue: "https://github.com/pikasTech/unidesk/issues/1560",
      primary: "platform-infra pipelines-as-code",
      primaryStatus: "bun scripts/cli.ts platform-infra pipelines-as-code status --target JD01",
      primaryHistory: "bun scripts/cli.ts platform-infra pipelines-as-code history --target JD01 --limit 10",
      archived: "cicd gitea-actions-poc",
      deprecated: "cicd branch-follower",
      note: "当前 source authority 由 GitHub PR merge -> Gitea mirror 更新；发布触发固定为 CLI release plan -> 手动 PaC webhook -> Tekton -> Argo/k8s runtime。Gitea Actions POC 与 branch-follower 仅保留只读历史观察。",
    },
    subcommands: [
      cicdNodeStatusHelp(),
      cicdGiteaActionsPocHelp(),
      branchFollowerHelp(),
    ],
  };
}

export async function runCicdCommand(config: UniDeskConfig | null, args: string[]): Promise<RenderedCliResult> {
  const top = args[0];
  if (top === undefined || top === "help" || top === "--help" || top === "-h") return renderMachine("cicd", cicdHelp(), "json");
  if (top === "status") return await runCicdNodeStatusCommand(config, args);
  if (top === "branch-follower") return await runBranchFollowerCommand(config, args);
  if (top === "gitea-actions-poc" || top === "gitea-builder-poc") return await runGiteaActionsPocCommand(config, args.slice(1), top);
  throw new Error("cicd usage: cicd status --node <NODE> | cicd gitea-actions-poc|branch-follower");
}
