"use strict";
/**
 * Kiro (AWS) "Power" host artifacts.
 *
 * A Kiro Power is a publishable knowledge package installed via "Add power from
 * GitHub <repo-url>". Verified against kiro.dev/docs/powers/{,create} and
 * kiro.dev/powers/submit (2026-05):
 *
 *   POWER.md     - root. YAML frontmatter: name, displayName, description,
 *                  keywords[] (the activation-keyword field), author. Body is
 *                  the "when to delegate" guidance. Submission requires a
 *                  "## License and support" footer with License (SPDX), a
 *                  Privacy Policy link, and a Support contact link.
 *   mcp.json     - root. { mcpServers: { <id>: { command, args, env } } }.
 *                  Kiro's own examples carry NO `type` field, so we omit it.
 *   steering/*   - subdir. Markdown workflow files. Kiro steering frontmatter
 *                  (`inclusion: always`) MUST be the first bytes of the file.
 *
 * These paths (POWER.md, mcp.json, steering/) do not collide with the Codex
 * (.codex-plugin/, .mcp.json, skills/, .agents/) or Cursor (.cursor/) outputs.
 *
 * Source of truth: AGENTS.md (host-neutral "when to delegate") for the POWER.md
 * body; rules/*.md for the steering files. The MCP server injects personas
 * server-side; the steering gives Kiro the same routing natively.
 *
 * @param {{ repoRoot:string, version:string }} ctx
 * @returns {Record<string,string>}
 */
const S = require("./_shared");

const KEYWORDS = [
  "architecture review",
  "security review",
  "second opinion",
  "consensus",
  "code review",
  "plan review",
  "debug",
  "grok",
  "openrouter",
  "gpt",
  "gemini",
  "deliberation",
];

const GENERATED_NOTE =
  "<!-- GENERATED by scripts/sync-hosts.js - edit the source under prompts/, AGENTS.md, rules/, or examples/, then regenerate. -->";

/**
 * The submission-mandated footer (kiro.dev/powers/submit): License (SPDX),
 * Privacy Policy link, Support contact link. deliberation stores no data
 * itself - provider calls go to whichever providers the user configures.
 */
const LICENSE_AND_SUPPORT_FOOTER = [
  "## License and support",
  "",
  "deliberation is licensed MIT (`MIT`).",
  "",
  "- Privacy: deliberation stores no data itself. Each delegation is forwarded to" +
    " the provider you configure (OpenAI/Codex, Gemini via the Antigravity CLI, the" +
    " xAI API, or an OpenRouter-compatible endpoint), under that provider's own" +
    " privacy policy. No prompts or responses are retained by this Power.",
  `- [Support](${S.REPO_URL}/issues)`,
].join("\n");

/**
 * Render a Kiro steering file: `inclusion: always` frontmatter (must be the
 * first bytes), then the generated-by note, then the body.
 * @param {string} body
 */
function steeringDoc(body) {
  return (
    "---\n" +
    "inclusion: always\n" +
    "---\n" +
    GENERATED_NOTE +
    "\n\n" +
    body.replace(/\s+$/, "") +
    "\n"
  );
}

/** A concise steering summary of the experts + tools (not a 15KB verbatim copy). */
function expertsSteering() {
  const expertLines = Object.keys(S.EXPERTS).map((k) => `- \`${k}\` - ${S.EXPERTS[k]}`);
  const cmdLines = Object.keys(S.COMMANDS).map((k) => `- \`${k}\` - ${S.COMMANDS[k]}`);
  return [
    "# Deliberation: when to delegate",
    "",
    "The deliberation MCP server exposes GPT (Codex), Gemini, Grok, and OpenRouter",
    "as expert subagents. Stay the primary agent; call a tool when a task benefits",
    "from a second opinion or cross-model review, then apply your own judgment.",
    "",
    "## Fan-out and single-provider tools",
    "",
    ...cmdLines,
    "",
    "## Expert personas",
    "",
    "Call as the tool, or pass via the `expert` argument on a fan-out tool to apply",
    "one persona to every delegate:",
    "",
    ...expertLines,
    "",
    "## Routing",
    "",
    "- Plan or architecture review before committing: `consensus`, `architect`, or `plan-reviewer`.",
    "- Security review of auth, untrusted input, or a new endpoint: `security-analyst`.",
    "- A second opinion, or after a fix has failed twice: `ask-all` or a single `ask-gpt` / `ask-gemini` / `ask-grok`.",
    "- A high-stakes or contested call: `consensus` for a single synthesized verdict.",
    "",
    "Pass full context in `prompt` - the experts do not share your session. Skip",
    "delegation for simple edits, the first attempt at a fix, and trivial questions.",
    "",
    "Advisory vs implementation: GPT (Codex) and Gemini can advise OR implement;",
    "Grok and OpenRouter are advisory-only (they cannot edit files).",
  ].join("\n");
}

/**
 * Strip Claude-Code-only regions from rules/triggers.md so the Kiro steering copy
 * is host-neutral: the "When a trigger matches" workflow (carries `${CLAUDE_PLUGIN_ROOT}`
 * + a `rules/orchestration.md` path that do not exist off Claude Code) and the fenced
 * examples that call the Claude bridge MCP tool names (`mcp__deliberation-<provider>__*`).
 * The host-neutral trigger TABLES stay.
 * @param {string} text @returns {string}
 */
function hostNeutralTriggers(text) {
  return text
    // The "When a trigger matches" numbered workflow (tolerate leading whitespace).
    .replace(/\nWhen a trigger matches:\n(?:[ \t]*\d+\..*\n)+/g, "\n")
    // A fenced block that mentions a Claude bridge MCP tool. Require a language tag
    // (`[a-z]+`, so a bare closing fence can't be mistaken for an opening one) and
    // temper BOTH halves with `(?!```)` so the match never crosses a fence boundary
    // (no over-matching into a later trigger table).
    .replace(/```[a-z]+\n(?:(?!```)[\s\S])*?mcp__deliberation(?:(?!```)[\s\S])*?```\n?/g, "")
    .replace(/\n{3,}/g, "\n\n");
}

function build(ctx) {
  /** @type {Record<string,string>} */
  const out = {};

  // POWER.md at the repo root. Frontmatter is the verified Kiro Power schema;
  // keywords[] is the activation-keyword field. Body = host-neutral AGENTS.md
  // (retitled), with the submission-mandated license/privacy/support footer.
  const agentsBody = S.readText(ctx.repoRoot, "AGENTS.md").replace(/^# AGENTS\.md\n/, "# Deliberation\n");
  // Scalars are JSON-quoted (valid YAML) so a future colon/quote/# in a shared
  // constant can never corrupt the frontmatter - same discipline as frontmatterDoc.
  out["POWER.md"] =
    "---\n" +
    `name: ${JSON.stringify("deliberation")}\n` +
    `displayName: ${JSON.stringify("Deliberation")}\n` +
    `description: ${JSON.stringify(S.SHORT_DESCRIPTION)}\n` +
    `keywords: ${JSON.stringify(KEYWORDS)}\n` +
    `author: ${JSON.stringify(S.AUTHOR.name)}\n` +
    "---\n" +
    GENERATED_NOTE +
    "\n\n" +
    agentsBody.replace(/\s+$/, "") +
    "\n\n" +
    LICENSE_AND_SUPPORT_FOOTER +
    "\n";

  // MCP server config at the Power root. Provider keys come from the host env
  // (OPENAI/Codex auth, XAI_API_KEY, OPENROUTER_API_KEY; Gemini via the agy CLI).
  // Kiro's own mcp.json examples omit a `type` field, so we follow that.
  out["mcp.json"] = S.json({
    mcpServers: {
      deliberation: {
        command: "npx",
        args: ["-y", S.MCP_PACKAGE],
        env: {},
      },
    },
  });

  // Steering: an "always" routing summary, plus the verbatim trigger catalogue.
  out["steering/deliberation.md"] = steeringDoc(expertsSteering());
  out["steering/deliberation-triggers.md"] = steeringDoc(hostNeutralTriggers(S.readText(ctx.repoRoot, "rules/triggers.md")));

  return out;
}

build.id = "kiro";
module.exports = build;
