const path = require("path");
const { routeTask, formatTextReport, listCheatsheet, loadMatrix } = require("../lib/route-engine");

module.exports = async function route(args, flags) {
  const rootDir = process.cwd();

  if (flags.list) {
    const matrix = loadMatrix(rootDir);
    if (!matrix) {
      console.error("No skill-routing-matrix.json found");
      process.exit(1);
    }
    console.log("\n" + listCheatsheet(matrix));
    return;
  }

  const text = args.filter((a) => !a.startsWith("--")).join(" ").trim();
  if (!text) {
    console.error('Provide task text: capint route "fix i18n bug"');
    process.exit(1);
  }

  const result = routeTask(text, rootDir);
  const { logDebug } = require("../lib/env-flags");
  logDebug(rootDir, {
    step: "route",
    capability: result.execution_intent?.capability,
    task_type: result.execution_intent?.explanation?.task_type_id,
    winner: result.execution_intent?.explanation?.winner
  });
  if (flags.json) {
    console.log(JSON.stringify(result, null, 2));
    return;
  }

  console.log(formatTextReport(result, { verbose: Boolean(flags.verbose || flags.v) }));
};
