const { routeTask } = require("../lib/route-engine");
const { validateExecutionIntent } = require("../lib/contract");

module.exports = async function consult(args, flags) {
  const rootDir = process.cwd();
  const text = args.filter((a) => !a.startsWith("--")).join(" ").trim();
  if (!text) {
    console.error('Provide task text: capint consult "fix i18n bug"');
    process.exit(1);
  }

  const result = routeTask(text, rootDir);
  if (result.error) {
    console.error(result.error);
    process.exit(1);
  }

  const contract = validateExecutionIntent(result.execution_intent);
  const payload = {
    mode: "dry_run",
    side_effects: false,
    request: text,
    recommendation: {
      capability: result.execution_intent.capability,
      resolution: result.execution_intent.resolution,
      memory: result.execution_intent.memory,
      plan: result.execution_intent.plan,
      confirm_default: result.execution_intent.confirm_default_option,
      verification_required: result.execution_intent.verification_required,
      provider_activation: result.execution_intent.provider_activation
    },
    weight: result.overall_weight,
    contract_valid: contract.valid,
    contract_errors: contract.errors,
    next_commands: [
      `capint route --json "${text.replace(/"/g, '\\"')}"`,
      "capint doctor",
      "capint status --json"
    ]
  };

  if (flags.json) {
    console.log(JSON.stringify(payload, null, 2));
    return;
  }

  console.log("\n## CapInt Consult (dry-run, no side effects)\n");
  console.log(`Task: ${text}`);
  console.log(`Capability: ${payload.recommendation.capability}`);
  console.log(`Resolution: ${payload.recommendation.resolution}`);
  console.log(`Memory: ${payload.recommendation.memory}`);
  console.log(`Plan: ${payload.recommendation.plan}`);
  console.log(`Weight: ${payload.weight}`);
  console.log(`Verification: ${payload.recommendation.verification_required ? "required" : "optional"}`);
  if (payload.recommendation.provider_activation) {
    const pa = payload.recommendation.provider_activation;
    console.log(
      `Providers: memory=${pa.memory?.activated ? "on" : "off"}, graph=${pa.graph?.activated ? "on" : "off"}`
    );
  }
  console.log("\nSuggested next:");
  for (const c of payload.next_commands) console.log(`  ${c}`);
  console.log("");
};
