"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var coupling_exports = {};
__export(coupling_exports, {
  register: () => register
});
module.exports = __toCommonJS(coupling_exports);
var path = __toESM(require("path"));
var import_ui = require("../ui");
const INSTABILITY_HIGH = 0.7;
const INSTABILITY_LOW = 0.3;
function instabilityBar(i) {
  const pct = Math.round(i * 10);
  const filled = "\u2588".repeat(pct);
  const empty = "\u2591".repeat(10 - pct);
  const color = i >= INSTABILITY_HIGH ? "\x1B[38;5;203m" : i <= INSTABILITY_LOW ? import_ui.green : "\x1B[33m";
  return `${color}${filled}${import_ui.dim}${empty}${import_ui.reset}`;
}
function instabilityLabel(i) {
  if (i >= INSTABILITY_HIGH) return `${"\x1B[38;5;203m"}unstable${import_ui.reset}`;
  if (i <= INSTABILITY_LOW) return `${import_ui.green}stable${import_ui.reset}`;
  return `${"\x1B[33m"}neutral${import_ui.reset}`;
}
function register(program) {
  program.command("coupling [projectPath]").description("Show package coupling metrics (Ca, Ce, instability)").option("--package <id>", "Show details for a single package (ID or name fragment)").option("--sort <by>", "Sort by: instability, ca, ce, name", "instability").option("--format <fmt>", "Output format: markdown, json", "markdown").action(async (projectPath, opts) => {
    const KiroGraph = (await Promise.resolve().then(() => require("../../index.js"))).default;
    const target = path.resolve(projectPath ?? process.cwd());
    const cg = await KiroGraph.open(target);
    if (!cg.isArchitectureEnabled()) {
      console.error(`
  ${"\x1B[33m"}\u26A0 Architecture analysis is disabled.${import_ui.reset}`);
      console.error(`  ${import_ui.dim}Enable it in .kirograph/config.json:${import_ui.reset} ${import_ui.violet}${import_ui.bold}"enableArchitecture": true${import_ui.reset}`);
      console.error(`  ${import_ui.dim}Then re-run:${import_ui.reset} ${import_ui.violet}${import_ui.bold}kirograph index${import_ui.reset}
`);
      cg.close();
      process.exit(1);
    }
    const arch = cg.getArchitecture();
    if (opts.format === "json") {
      const out = opts.package ? arch.coupling.filter((c) => c.packageId.includes(opts.package) || arch.packages.find((p) => p.id === c.packageId)?.name.includes(opts.package)) : arch.coupling;
      console.log(JSON.stringify(out, null, 2));
      cg.close();
      return;
    }
    if (opts.package) {
      const pkg = arch.packages.find(
        (p) => p.id.includes(opts.package) || p.name.toLowerCase().includes(opts.package.toLowerCase())
      );
      if (!pkg) {
        console.error(`
  ${"\x1B[38;5;203m"}\u2717 Package not found: ${opts.package}${import_ui.reset}
`);
        cg.close();
        process.exit(1);
      }
      const c = arch.coupling.find((x) => x.packageId === pkg.id);
      console.log(`
  ${(0, import_ui.section)(pkg.name)}  ${import_ui.dim}${pkg.path}${import_ui.reset}
`);
      console.log((0, import_ui.renderTable)([
        ["Afferent Ca", String(c?.afferent ?? 0)],
        ["Efferent Ce", String(c?.efferent ?? 0)],
        ["Instability", c ? `${(c.instability * 100).toFixed(0)}%` : "n/a"]
      ]));
      const incoming = arch.packageDeps.filter((d) => d.targetPkg === pkg.id);
      if (incoming.length > 0) {
        console.log(`
  ${(0, import_ui.label)("Depended on by")}  ${import_ui.dim}(${incoming.length})${import_ui.reset}
`);
        for (const d of incoming) {
          const name = arch.packages.find((p) => p.id === d.sourcePkg)?.name ?? d.sourcePkg;
          console.log(`  ${import_ui.dim}\u2190${import_ui.reset}  ${import_ui.violet}${name}${import_ui.reset}  ${import_ui.dim}(${d.depCount} import${d.depCount !== 1 ? "s" : ""})${import_ui.reset}`);
        }
      }
      const outgoing = arch.packageDeps.filter((d) => d.sourcePkg === pkg.id);
      if (outgoing.length > 0) {
        console.log(`
  ${(0, import_ui.label)("Depends on")}  ${import_ui.dim}(${outgoing.length})${import_ui.reset}
`);
        for (const d of outgoing) {
          const name = arch.packages.find((p) => p.id === d.targetPkg)?.name ?? d.targetPkg;
          console.log(`  ${import_ui.dim}\u2192${import_ui.reset}  ${import_ui.violet}${name}${import_ui.reset}  ${import_ui.dim}(${d.depCount} import${d.depCount !== 1 ? "s" : ""})${import_ui.reset}`);
        }
      }
      console.log();
      cg.close();
      return;
    }
    let coupling = arch.coupling.slice();
    const pkgById = new Map(arch.packages.map((p) => [p.id, p]));
    switch (opts.sort) {
      case "ca":
        coupling.sort((a, b) => b.afferent - a.afferent);
        break;
      case "ce":
        coupling.sort((a, b) => b.efferent - a.efferent);
        break;
      case "name":
        coupling.sort((a, b) => (pkgById.get(a.packageId)?.name ?? "").localeCompare(pkgById.get(b.packageId)?.name ?? ""));
        break;
      default:
        coupling.sort((a, b) => b.instability - a.instability);
        break;
    }
    console.log(`
  ${(0, import_ui.section)("Coupling Metrics")}  ${import_ui.dim}sorted by ${opts.sort}${import_ui.reset}
`);
    if (coupling.length === 0) {
      console.log(`  ${import_ui.dim}No coupling data. Run ${import_ui.reset}${import_ui.violet}${import_ui.bold}kirograph index${import_ui.reset}${import_ui.dim} with enableArchitecture=true.${import_ui.reset}
`);
      cg.close();
      return;
    }
    const nameW = Math.max(...coupling.map((c) => (pkgById.get(c.packageId)?.name ?? c.packageId).length), 4);
    console.log(`  ${import_ui.dim}${"Package".padEnd(nameW)}  Ca   Ce   Instability${import_ui.reset}`);
    console.log(`  ${import_ui.dim}${"\u2500".repeat(nameW + 26)}${import_ui.reset}`);
    for (const c of coupling) {
      const pkg = pkgById.get(c.packageId);
      const name = (pkg?.name ?? c.packageId).padEnd(nameW);
      const ca = String(c.afferent).padStart(3);
      const ce = String(c.efferent).padStart(3);
      const pct = `${(c.instability * 100).toFixed(0)}%`.padStart(4);
      const bar = instabilityBar(c.instability);
      const lbl = instabilityLabel(c.instability);
      console.log(`  ${import_ui.violet}${name}${import_ui.reset}  ${import_ui.dim}${ca}${import_ui.reset}  ${import_ui.dim}${ce}${import_ui.reset}  ${bar} ${pct}  ${lbl}`);
    }
    const avgInstability = coupling.length > 0 ? coupling.reduce((s, c) => s + c.instability, 0) / coupling.length : 0;
    console.log(`
  ${(0, import_ui.label)("Packages")}  ${(0, import_ui.value)(String(coupling.length))}    ${(0, import_ui.label)("Avg instability")}  ${(0, import_ui.value)(`${(avgInstability * 100).toFixed(0)}%`)}
`);
    cg.close();
  });
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  register
});
//# sourceMappingURL=coupling.js.map
