import { defineCommand } from '@kb-labs/sdk';
import { runTests } from '@kb-labs/quality-core/tests';
import { CACHE_KEYS } from '@kb-labs/quality-contracts';

// src/cli/commands/check-tests.ts
var check_tests_default = defineCommand({
  id: "quality:check-tests",
  description: "Run tests and track coverage across monorepo",
  handler: {
    async execute(ctx, input) {
      const { ui, platform } = ctx;
      const flags = input.flags ?? input;
      const cacheKey = `${CACHE_KEYS.TESTS}:${flags.package || "all"}`;
      if (!flags.refresh) {
        const cached = await platform.cache.get(cacheKey);
        if (cached) {
          outputTestResults({ ...cached, cached: true }, flags, ui);
          return { exitCode: cached.failing > 0 ? 1 : 0, result: cached };
        }
      }
      const result = await runTests(ctx.cwd, {
        packageFilter: flags.package,
        timeout: flags.timeout ? Number(flags.timeout) : 6e4,
        withCoverage: flags["with-coverage"],
        coverageOnly: flags["coverage-only"]
      });
      await platform.cache.set(cacheKey, result, 5 * 60 * 1e3);
      await platform.analytics.track("quality:check-tests", {
        packageFilter: flags.package || "all",
        totalPackages: result.totalPackages,
        passing: result.passing,
        failing: result.failing,
        withCoverage: flags["with-coverage"],
        cached: false
      });
      outputTestResults({ ...result, cached: false }, flags, ui);
      return {
        exitCode: result.failing > 0 ? 1 : 0,
        result,
        meta: { cached: false }
      };
    }
  }
});
function outputTestResults(result, flags, ui) {
  if (flags.json) {
    ui?.json?.(result);
    return;
  }
  const sections = [];
  const statusIcon = result.failing === 0 ? "\u2705" : "\u274C";
  const statusText = result.failing === 0 ? "All tests passing" : "Test failures detected";
  const statusItems = [
    `${statusIcon} ${statusText}`,
    `Total packages: ${result.totalPackages}`,
    `Passing: ${result.passing}`,
    result.failing > 0 ? `Failing: ${result.failing}` : null,
    result.skipped > 0 ? `Skipped: ${result.skipped} (no test script)` : null
  ].filter(Boolean);
  sections.push({ header: "Test Status", items: statusItems });
  if (result.summary.totalTests > 0) {
    const summaryItems2 = [
      `Total tests: ${result.summary.totalTests}`,
      `Passed: ${result.summary.passedTests}`,
      result.summary.failedTests > 0 ? `Failed: ${result.summary.failedTests}` : null
    ].filter(Boolean);
    sections.push({ header: "Test Summary", items: summaryItems2 });
  }
  if (result.failures.length > 0) {
    const failureItems = [];
    for (const failure of result.failures.slice(0, 5)) {
      failureItems.push(`\u274C ${failure.package}`);
      if (failure.failedTests && failure.totalTests) {
        failureItems.push(`  ${failure.failedTests}/${failure.totalTests} tests failed`);
      }
      const firstLine = failure.error.split("\n")[0];
      failureItems.push(`  ${firstLine?.substring(0, 80) || "Test failed"}`);
    }
    if (result.failures.length > 5) {
      failureItems.push(`... and ${result.failures.length - 5} more failures`);
    }
    sections.push({ header: "Failed Packages", items: failureItems });
  }
  if (result.coverage.packages.length > 0) {
    const coverageItems = [];
    coverageItems.push(`Average coverage: ${result.coverage.avgCoverage.toFixed(1)}%`);
    coverageItems.push("");
    const topPackages = result.coverage.packages.sort((a, b) => b.lines - a.lines).slice(0, 5);
    for (const pkg of topPackages) {
      coverageItems.push(`${pkg.name}`);
      coverageItems.push(
        `  Lines: ${pkg.lines.toFixed(1)}% | Statements: ${pkg.statements.toFixed(1)}% | Functions: ${pkg.functions.toFixed(1)}% | Branches: ${pkg.branches.toFixed(1)}%`
      );
    }
    if (result.coverage.packages.length > 5) {
      coverageItems.push(`... and ${result.coverage.packages.length - 5} more packages`);
    }
    sections.push({ header: "Coverage", items: coverageItems });
  }
  const summaryItems = [
    `Duration: ${(result.duration / 1e3).toFixed(1)}s`,
    result.cached ? "\u{1F4BE} Cached (use --refresh to re-run)" : "\u{1F504} Fresh run"
  ];
  sections.push({ header: "Summary", items: summaryItems });
  const title = result.failing === 0 ? "\u2705 All Tests Passed" : `\u274C ${result.failing} Package(s) with Test Failures`;
  ui?.success?.("Test run completed", {
    title,
    sections
  });
}

export { check_tests_default as default };
//# sourceMappingURL=check-tests.js.map
//# sourceMappingURL=check-tests.js.map