const { runDoctor, runStatus } = require("./doctor");
const { routeTask } = require("./route-engine");
const { checkIdeProjection } = require("./ide-sync");
const { logDebug } = require("./env-flags");

function runPipeline(rootDir, { task = null, skipIde = false } = {}) {
  const steps = [];
  let pass = true;

  const doctor = runDoctor(rootDir);
  steps.push({
    id: "doctor",
    ok: doctor.pass,
    summary: doctor.pass ? "PASS" : "FAIL",
    detail: doctor
  });
  if (!doctor.pass) pass = false;

  const status = runStatus(rootDir);
  steps.push({
    id: "status",
    ok: status.doctor_pass,
    summary: `${status.skills_on_disk} skills · matrix ${status.matrix_version || "—"}`,
    detail: {
      skills_on_disk: status.skills_on_disk,
      matrix_version: status.matrix_version,
      warnings_count: status.warnings_count,
      issues_count: status.issues_count
    }
  });

  if (!skipIde) {
    const checks = checkIdeProjection(rootDir);
    const ideOk = checks.every((c) => c.ok || c.name === "AGENTS.md");
    const missing = checks.filter((c) => !c.ok).map((c) => c.path);
    steps.push({
      id: "ide_check",
      ok: ideOk,
      advisory: !ideOk,
      summary: ideOk ? "projections OK" : `missing: ${missing.join(", ")} — run capint ide sync`,
      detail: checks
    });
  }

  let route = null;
  if (task) {
    route = routeTask(task, rootDir);
    const ok = !route.error && route.execution_intent?.resolution_status !== "not_installed";
    steps.push({
      id: "route",
      ok,
      summary: route.error
        ? route.error
        : `${route.execution_intent.capability} (${route.execution_intent.resolution_status || "installed"})`,
      detail: route.error ? { error: route.error } : { execution_intent: route.execution_intent }
    });
    if (!ok) pass = false;
    logDebug(rootDir, {
      step: "pipeline.route",
      capability: route.execution_intent?.capability,
      task_type: route.execution_intent?.explanation?.task_type_id
    });
  }

  return { pass, steps, route, doctor, status };
}

module.exports = { runPipeline };
