import { defineCommand, useConfig } from '@kb-labs/sdk';
import { getWorkspacePackages, runQA, loadBaseline, compareWithBaseline, resolveCategories, groupResults, buildDetailedJsonReport, buildRunReport, buildDetailedRunReport } from '@kb-labs/qa-core';

// src/cli/commands/qa-run.ts
var CHECK_ICONS = {
  build: "\u{1F528}",
  lint: "\u{1F50D}",
  typeCheck: "\u{1F4D8}",
  test: "\u{1F9EA}"
};
var STATUS_MARKS = {
  pass: "\u2713",
  fail: "\u2717",
  skip: "\u2212"
};
var qa_run_default = defineCommand({
  id: "qa:run",
  description: "Run all QA checks (build, lint, types, tests)",
  handler: {
    async execute(ctx, input) {
      const { ui } = ctx;
      const { flags } = input;
      const rootDir = ctx.cwd;
      let config;
      try {
        config = await Promise.race([
          useConfig(),
          new Promise((resolve) => {
            setTimeout(() => resolve(void 0), 3e3);
          })
        ]);
      } catch {
      }
      const scopeKey = flags.scope;
      const checks = (scopeKey ? config?.scopes?.[scopeKey]?.checks : void 0) ?? config?.checks;
      const rawSkip = flags["skip-check"];
      const skipChecks = Array.isArray(rawSkip) ? rawSkip : rawSkip ? [rawSkip] : [];
      const isJson = !!flags.json;
      let totalPkgs = 0;
      if (!isJson) {
        try {
          const pkgs = getWorkspacePackages(rootDir, {
            package: flags.package,
            repo: flags.repo,
            scope: scopeKey
          }, config?.packages);
          totalPkgs = pkgs.length;
        } catch {
        }
      }
      const counters = {};
      let currentPhase = "";
      const startTime = Date.now();
      const { results, packages } = await runQA({
        rootDir,
        skipChecks,
        noCache: !!flags["no-cache"],
        package: flags.package,
        repo: flags.repo,
        scope: scopeKey,
        packagesConfig: config?.packages,
        checks,
        onProgress: (phase, pkg, status, durationMs2) => {
          if (isJson) {
            return;
          }
          if (phase !== currentPhase) {
            currentPhase = phase;
            counters[phase] = 0;
            const phaseIcon = CHECK_ICONS[phase] ?? "\u25B8";
            const elapsed = ((Date.now() - startTime) / 1e3).toFixed(0);
            process.stdout.write(`
${phaseIcon} ${phase} (${elapsed}s elapsed)
`);
          }
          counters[phase] = (counters[phase] ?? 0) + 1;
          const count = counters[phase];
          const total = totalPkgs || "?";
          const mark = STATUS_MARKS[status] ?? status;
          const time = durationMs2 != null ? ` (${(durationMs2 / 1e3).toFixed(1)}s)` : "";
          process.stdout.write(`  [${count}/${total}] ${pkg} ${mark}${time}
`);
        }
      });
      const durationMs = Date.now() - startTime;
      if (!isJson) {
        const elapsed = (durationMs / 1e3).toFixed(1);
        process.stdout.write(`
Completed in ${elapsed}s

`);
      }
      const analytics = ctx.platform.analytics;
      if (analytics) {
        const hasFails2 = Object.values(results).some((r) => r.failed.length > 0);
        for (const ct of Object.keys(results)) {
          const r = results[ct];
          await analytics.track("qa.check.completed", {
            checkType: ct,
            status: r.failed.length > 0 ? "failed" : "passed",
            passed: r.passed.length,
            failed: r.failed.length,
            skipped: r.skipped.length
          });
        }
        const checkKeys = Object.keys(results);
        await analytics.track("qa.run.completed", {
          status: hasFails2 ? "failed" : "passed",
          ...Object.fromEntries(checkKeys.flatMap((ct) => [
            [`${ct}Passed`, results[ct].passed.length],
            [`${ct}Failed`, results[ct].failed.length]
          ])),
          totalPassed: checkKeys.reduce((s, ct) => s + results[ct].passed.length, 0),
          totalFailed: checkKeys.reduce((s, ct) => s + results[ct].failed.length, 0),
          totalSkipped: checkKeys.reduce((s, ct) => s + results[ct].skipped.length, 0),
          durationMs
        });
      }
      const baseline = loadBaseline(rootDir);
      const diff = baseline ? compareWithBaseline(results, baseline) : null;
      const categoryMap = resolveCategories(packages, config);
      const grouped = groupResults(results, packages, categoryMap, config);
      if (isJson) {
        const report = buildDetailedJsonReport(results, grouped, diff);
        ui?.json?.({ ...report, skippedChecks: skipChecks });
        return { exitCode: report.status === "failed" ? 1 : 0 };
      }
      if (skipChecks.length > 0) {
        ui?.success?.("Skipped checks", {
          title: "Skipped checks",
          sections: [{ header: "", items: skipChecks.map((c) => `  - ${c}`) }]
        });
      }
      if (flags.summary) {
        const sections = buildRunReport(results, diff);
        for (const section of sections) {
          ui?.success?.(section.header, {
            title: section.header,
            sections: [{ header: "", items: section.lines }]
          });
        }
      } else {
        const sections = buildDetailedRunReport(grouped, diff);
        for (const section of sections) {
          ui?.success?.(section.header, {
            title: section.header,
            sections: [{ header: "", items: section.lines }]
          });
        }
      }
      const hasFails = Object.values(results).some((r) => r.failed.length > 0);
      return { exitCode: hasFails ? 1 : 0 };
    }
  }
});

export { qa_run_default as default };
//# sourceMappingURL=qa-run.js.map
//# sourceMappingURL=qa-run.js.map