import { defineCommand, useConfig } from '@kb-labs/sdk';
import { getWorkspacePackages, runCustomChecks, createHistoryEntry, appendEntry, buildJsonReport } from '@kb-labs/qa-core';

// src/cli/commands/qa-check.ts
var qaCheckFlags = {
  id: {
    type: "string",
    description: "Check ID to run (must match a check in qa.checks config)",
    demandOption: true
  },
  base: {
    type: "string",
    description: "Base branch/commit for diff strategies (diffOnly, newFiles). Default: main",
    default: "main"
  },
  context: {
    type: "string",
    description: 'JSON context to attach to the history entry (e.g. {"taskId":"123","agentId":"claude"})'
  },
  json: {
    type: "boolean",
    description: "Output structured JSON report",
    default: false
  },
  save: {
    type: "boolean",
    description: "Save result to history after running",
    default: true
  }
};
var qa_check_default = defineCommand({
  id: "qa:check",
  description: "Run a single QA check atomically and optionally save to history",
  handler: {
    async execute(ctx, input) {
      const { ui } = ctx;
      const { flags } = input;
      const rootDir = ctx.cwd;
      const checkId = flags.id;
      const base = flags.base ?? "main";
      const isJson = !!flags.json;
      const shouldSave = flags.save !== false;
      let config;
      try {
        config = await Promise.race([
          useConfig(),
          new Promise((resolve) => {
            setTimeout(() => resolve(void 0), 3e3);
          })
        ]);
      } catch {
      }
      const allChecks = config?.checks ?? [];
      const checkConfig = allChecks.find((c) => c.id === checkId);
      if (!checkConfig) {
        const msg = `Check "${checkId}" not found in qa.checks config`;
        if (isJson) {
          ui?.json?.({ status: "error", message: msg });
        } else {
          ui?.error?.(msg, { title: "QA Check Error" });
        }
        return { exitCode: 1 };
      }
      let runContext;
      if (flags.context) {
        try {
          runContext = JSON.parse(flags.context);
        } catch {
          const msg = `Invalid JSON in --context: ${flags.context}`;
          if (isJson) {
            ui?.json?.({ status: "error", message: msg });
          } else {
            ui?.error?.(msg, { title: "QA Check Error" });
          }
          return { exitCode: 1 };
        }
      }
      const packages = getWorkspacePackages(rootDir, {}, config?.packages);
      const results = runCustomChecks(
        [checkConfig],
        packages,
        rootDir,
        void 0,
        base
      );
      const checkResult = results[checkId];
      const hasFailed = checkResult ? checkResult.failed.length > 0 : false;
      if (shouldSave) {
        const entry = createHistoryEntry(results, rootDir, packages, runContext);
        appendEntry(rootDir, entry, allChecks);
      }
      const severity = checkConfig.severity ?? "blocker";
      const report = buildJsonReport(results, null, [checkConfig]);
      if (isJson) {
        ui?.json?.(report);
      } else {
        if (hasFailed) {
          const findings = severity === "warning" ? report.warnings : report.blockers;
          const checkFindings = findings.find((f) => f.check === checkId);
          if (checkFindings) {
            ui?.error?.(`Check "${checkId}" failed`, {
              title: `${severity === "warning" ? "\u26A0" : "\u2717"} ${checkId}`,
              sections: [{
                header: "",
                items: checkFindings.items.map(
                  (item) => `  ${item.target}: ${item.message}${item.fix ? ` \u2192 ${item.fix}` : ""}`
                )
              }]
            });
          }
        } else {
          ui?.success?.(`Check "${checkId}" passed`, { title: `\u2713 ${checkId}` });
        }
      }
      const shouldFail = hasFailed && severity === "blocker";
      return { exitCode: shouldFail ? 1 : 0 };
    }
  }
});

export { qa_check_default as default, qaCheckFlags };
//# sourceMappingURL=qa-check.js.map
//# sourceMappingURL=qa-check.js.map