import { defineCommand } from '@kb-labs/sdk';
import { buildDependencyGraph, getBuildOrderForPackage, topologicalSort } from '@kb-labs/quality-core/graph';

// src/cli/commands/build-order.ts
var build_order_default = defineCommand({
  id: "quality:build-order",
  description: "Calculate build order using topological sort",
  handler: {
    async execute(ctx, input) {
      const { ui } = ctx;
      const flags = input.flags ?? input;
      const graph = buildDependencyGraph(ctx.cwd);
      let result;
      if (flags.package) {
        result = getBuildOrderForPackage(graph, flags.package);
      } else {
        result = topologicalSort(graph);
      }
      if (result.circular.length > 0) {
        ui?.error?.(
          `Found ${result.circular.length} circular dependencies. Build order cannot be determined.`
        );
        outputCircularDependencies(result.circular, ui);
        return { exitCode: 1, result };
      }
      outputBuildOrder(result, flags, ui);
      return { exitCode: 0, result };
    }
  }
});
function outputBuildOrder(result, flags, ui) {
  if (flags.json) {
    ui?.json?.(result);
    return;
  }
  if (flags.script) {
    ui?.write?.("#!/bin/bash");
    ui?.write?.("# Generated build script");
    ui?.write?.("set -e");
    ui?.write?.("");
    for (let i = 0; i < result.layers.length; i++) {
      const layer = result.layers[i];
      if (!layer) {
        continue;
      }
      ui?.write?.(`# Layer ${i + 1} (${layer.length} packages)`);
      for (const pkg of layer) {
        ui?.write?.(`pnpm --filter "${pkg}" run build`);
      }
      ui?.write?.("");
    }
    return;
  }
  const sections = [];
  if (flags.layers) {
    const layerItems = [];
    for (let i = 0; i < result.layers.length; i++) {
      const layer = result.layers[i];
      if (!layer) {
        continue;
      }
      layerItems.push(`Layer ${i + 1}: ${layer.length} packages (can build in parallel)`);
      for (const pkg of layer) {
        layerItems.push(`  \u2022 ${pkg}`);
      }
      layerItems.push("");
    }
    sections.push({ header: "Build Layers", items: layerItems });
  } else {
    const orderItems = result.sorted.map((pkg, idx) => `${idx + 1}. ${pkg}`);
    sections.push({ header: "Build Order", items: orderItems });
  }
  sections.push({
    header: "Summary",
    items: [
      `Total packages: ${result.sorted.length}`,
      `Build layers: ${result.layers.length}`,
      `Circular dependencies: ${result.circular.length}`
    ]
  });
  const title = flags.package ? `\u{1F4E6} Build Order for ${flags.package}` : "\u{1F4E6} Monorepo Build Order";
  ui?.success?.("Build order calculated successfully", {
    title,
    sections
  });
}
function outputCircularDependencies(cycles, ui) {
  const sections = [];
  for (let i = 0; i < cycles.length; i++) {
    const cycle = cycles[i];
    if (!cycle) {
      continue;
    }
    sections.push({
      header: `Cycle ${i + 1}`,
      items: cycle.map((pkg, idx) => {
        if (idx === cycle.length - 1) {
          const firstPkg = cycle[0];
          return `  ${pkg} \u2192 ${firstPkg ?? "?"} (circular!)`;
        }
        return `  ${pkg} \u2192`;
      })
    });
  }
  ui?.error?.("Circular dependencies detected", {
    title: "\u26A0\uFE0F Circular Dependencies",
    sections
  });
}

export { build_order_default as default };
//# sourceMappingURL=build-order.js.map
//# sourceMappingURL=build-order.js.map