#!/usr/bin/env node
import { fileURLToPath as __fileURLToPath } from 'url';
import { dirname as __pathDirname } from 'path';
const __filename = __fileURLToPath(import.meta.url);
const __dirname = __pathDirname(__filename);
import { Command } from "commander";
import chalk from "chalk";
import ora from "ora";
import inquirer from "inquirer";
import {
  PostTaskHooks
} from "../../integrations/claude-code/post-task-hooks.js";
import { FrameManager } from "../../core/context/index.js";
import Database from "better-sqlite3";
import * as fs from "fs/promises";
import * as path from "path";
function createQualityCommand() {
  const cmd = new Command("quality").description("Manage post-task quality gates and automation").option("--enable", "Enable quality gates").option("--disable", "Disable quality gates").option("--status", "Show quality gate status").option("--config", "Configure quality gates").option("--run", "Run quality gates manually").option("--history", "Show quality gate history").option("--setup", "Interactive setup wizard").action(async (options) => {
    const spinner = ora();
    try {
      const projectRoot = await getProjectRoot();
      const dbPath = path.join(
        projectRoot,
        ".stackmemory",
        "db",
        "stackmemory.db"
      );
      try {
        await fs.access(dbPath);
      } catch {
        console.error(chalk.red("\u2717 StackMemory not initialized"));
        console.log(chalk.yellow("Run: stackmemory init"));
        process.exit(1);
      }
      const db = new Database(dbPath);
      const frameManager = new FrameManager(db);
      if (options.enable) {
        await enableQualityGates(projectRoot, frameManager, db, spinner);
      } else if (options.disable) {
        await disableQualityGates(projectRoot, spinner);
      } else if (options.status) {
        await showStatus(projectRoot, frameManager, db);
      } else if (options.config) {
        await configureQualityGates(projectRoot);
      } else if (options.run) {
        await runQualityGates(projectRoot, frameManager, db, spinner);
      } else if (options.history) {
        await showHistory(frameManager);
      } else if (options.setup) {
        await setupWizard(projectRoot, frameManager, db);
      } else {
        await showStatus(projectRoot, frameManager, db);
      }
    } catch (error) {
      spinner.fail(chalk.red(`Error: ${error}`));
      process.exit(1);
    }
  });
  return cmd;
}
async function enableQualityGates(projectRoot, frameManager, db, spinner) {
  spinner.start("Enabling quality gates...");
  try {
    const config = await loadConfig(projectRoot);
    config.qualityGates = {
      ...config.qualityGates,
      runTests: true,
      runCodeReview: true,
      runLinter: true
    };
    const hooks = new PostTaskHooks(frameManager, db, config);
    await hooks.initialize();
    await saveConfig(projectRoot, config);
    await createServiceFile(projectRoot);
    spinner.succeed(chalk.green("\u2705 Quality gates enabled"));
    console.log(chalk.bold("\n\u{1F50D} Quality Gates Active:"));
    console.log("  \u2022 Auto-run tests after code changes");
    console.log("  \u2022 Auto-run linter on file saves");
    console.log("  \u2022 Auto-trigger code review on task completion");
    console.log("  \u2022 Real-time file change monitoring");
    console.log(chalk.gray("\nDisable with: stackmemory quality --disable"));
  } catch (error) {
    spinner.fail(chalk.red(`Failed to enable quality gates: ${error}`));
  }
}
async function disableQualityGates(projectRoot, spinner) {
  spinner.start("Disabling quality gates...");
  try {
    const config = await loadConfig(projectRoot);
    config.qualityGates = {
      ...config.qualityGates,
      runTests: false,
      runCodeReview: false,
      runLinter: false
    };
    await saveConfig(projectRoot, config);
    const serviceFile = path.join(
      projectRoot,
      ".stackmemory",
      "quality.service"
    );
    try {
      await fs.unlink(serviceFile);
    } catch {
    }
    spinner.succeed(chalk.green("\u2705 Quality gates disabled"));
  } catch (error) {
    spinner.fail(chalk.red(`Failed to disable quality gates: ${error}`));
  }
}
async function showStatus(projectRoot, frameManager, db) {
  console.log(chalk.bold("\n\u{1F4CA} Quality Gates Status\n"));
  try {
    const config = await loadConfig(projectRoot);
    const isEnabled = config.qualityGates?.runTests || config.qualityGates?.runCodeReview || config.qualityGates?.runLinter;
    console.log(
      `Status: ${isEnabled ? chalk.green("\u2705 Enabled") : chalk.yellow("\u26A0\uFE0F Disabled")}`
    );
    console.log("\nGates:");
    console.log(
      `  Tests: ${config.qualityGates?.runTests ? "\u2705" : "\u274C"} ${getTestCommand(config)}`
    );
    console.log(
      `  Linter: ${config.qualityGates?.runLinter ? "\u2705" : "\u274C"} ${getLintCommand(config)}`
    );
    console.log(
      `  Code Review: ${config.qualityGates?.runCodeReview ? "\u2705" : "\u274C"}`
    );
    console.log(
      `  Coverage: ${config.qualityGates?.requireTestCoverage ? "\u2705" : "\u274C"}`
    );
    if (config.testFrameworks?.detected.length) {
      console.log("\nDetected Frameworks:");
      config.testFrameworks.detected.forEach((fw) => {
        console.log(`  \u2022 ${fw}`);
      });
    }
    const recentResults = await getRecentQualityResults(frameManager);
    if (recentResults.length > 0) {
      console.log("\nRecent Results:");
      recentResults.slice(0, 3).forEach((result) => {
        const icon = result.passed ? "\u2705" : "\u274C";
        console.log(
          `  ${icon} ${result.frameName} (${new Date(result.timestamp).toLocaleString()})`
        );
      });
    }
  } catch (error) {
    console.error(chalk.red("Failed to get status:", error));
  }
}
async function configureQualityGates(projectRoot) {
  console.log(chalk.bold("\n\u2699\uFE0F Quality Gates Configuration\n"));
  try {
    const config = await loadConfig(projectRoot);
    const answers = await inquirer.prompt([
      {
        type: "confirm",
        name: "runTests",
        message: "Auto-run tests after code changes?",
        default: config.qualityGates?.runTests ?? true
      },
      {
        type: "confirm",
        name: "runLinter",
        message: "Auto-run linter on file changes?",
        default: config.qualityGates?.runLinter ?? true
      },
      {
        type: "confirm",
        name: "runCodeReview",
        message: "Auto-trigger code review on task completion?",
        default: config.qualityGates?.runCodeReview ?? true
      },
      {
        type: "confirm",
        name: "requireTestCoverage",
        message: "Require test coverage checks?",
        default: config.qualityGates?.requireTestCoverage ?? false
      },
      {
        type: "confirm",
        name: "blockOnFailure",
        message: "Block further work when quality gates fail?",
        default: config.qualityGates?.blockOnFailure ?? false
      },
      {
        type: "input",
        name: "testCommand",
        message: "Custom test command (leave empty for auto-detect):",
        default: config.testFrameworks?.testCommand || ""
      },
      {
        type: "input",
        name: "lintCommand",
        message: "Custom lint command (leave empty for auto-detect):",
        default: config.testFrameworks?.lintCommand || ""
      }
    ]);
    config.qualityGates = {
      runTests: answers.runTests,
      runLinter: answers.runLinter,
      runCodeReview: answers.runCodeReview,
      requireTestCoverage: answers.requireTestCoverage,
      blockOnFailure: answers.blockOnFailure
    };
    config.testFrameworks = {
      ...config.testFrameworks,
      testCommand: answers.testCommand || config.testFrameworks?.testCommand,
      lintCommand: answers.lintCommand || config.testFrameworks?.lintCommand
    };
    await saveConfig(projectRoot, config);
    console.log(chalk.green("\n\u2705 Configuration saved"));
    console.log(chalk.gray("Enable with: stackmemory quality --enable"));
  } catch (error) {
    console.error(chalk.red("Configuration failed:", error));
  }
}
async function runQualityGates(projectRoot, frameManager, db, spinner) {
  spinner.start("Running quality gates...");
  try {
    const config = await loadConfig(projectRoot);
    const hooks = new PostTaskHooks(frameManager, db, config);
    const mockEvent = {
      taskType: "task_complete",
      frameId: "manual-run",
      frameName: "Manual quality gate run",
      files: await getRecentlyModifiedFiles(projectRoot),
      changes: { added: 0, removed: 0, modified: 1 },
      metadata: { trigger: "manual" }
    };
    const results = await hooks.runQualityGates(mockEvent);
    spinner.succeed(chalk.green("\u2705 Quality gates completed"));
    console.log(chalk.bold("\n\u{1F4CB} Quality Gate Results:\n"));
    results.forEach((result) => {
      const icon = result.passed ? "\u2705" : "\u274C";
      const duration = result.duration < 1e3 ? `${result.duration}ms` : `${Math.round(result.duration / 1e3)}s`;
      console.log(`${icon} ${result.gate} (${duration})`);
      if (!result.passed && result.issues) {
        result.issues.slice(0, 3).forEach((issue) => {
          console.log(
            `   ${issue.severity === "error" ? "\u274C" : "\u26A0\uFE0F"} ${issue.message}`
          );
        });
        if (result.issues.length > 3) {
          console.log(
            chalk.gray(`   ... and ${result.issues.length - 3} more issues`)
          );
        }
      }
    });
    const allPassed = results.every((r) => r.passed);
    if (allPassed) {
      console.log(chalk.green("\n\u{1F389} All quality gates passed!"));
    } else {
      console.log(
        chalk.yellow("\n\u26A0\uFE0F Some quality gates failed. See details above.")
      );
    }
  } catch (error) {
    spinner.fail(chalk.red(`Quality gates failed: ${error}`));
  }
}
async function showHistory(frameManager) {
  console.log(chalk.bold("\n\u{1F4C8} Quality Gate History\n"));
  try {
    const results = await getRecentQualityResults(frameManager);
    if (results.length === 0) {
      console.log(chalk.gray("No quality gate history found"));
      return;
    }
    results.slice(0, 10).forEach((result, index) => {
      const icon = result.passed ? "\u2705" : "\u274C";
      const date = new Date(result.timestamp).toLocaleDateString();
      const time = new Date(result.timestamp).toLocaleTimeString();
      console.log(`${icon} ${result.frameName}`);
      console.log(chalk.gray(`   ${date} ${time} - ${result.duration}ms`));
      if (result.gates) {
        result.gates.forEach((gate) => {
          const gateIcon = gate.passed ? "  \u2713" : "  \u2717";
          console.log(chalk.gray(`${gateIcon} ${gate.gate}`));
        });
      }
      if (index < results.length - 1) console.log("");
    });
  } catch (error) {
    console.error(chalk.red("Failed to get history:", error));
  }
}
async function setupWizard(projectRoot, frameManager, db) {
  console.log(chalk.bold("\u{1F9D9} Quality Gates Setup Wizard\n"));
  console.log(
    "This wizard will help you configure automatic quality gates for your project."
  );
  console.log(
    "Quality gates run automatically after Claude completes tasks.\n"
  );
  const packageJsonPath = path.join(projectRoot, "package.json");
  let projectType = "unknown";
  const detectedFrameworks = [];
  try {
    const packageJson = JSON.parse(await fs.readFile(packageJsonPath, "utf-8"));
    const deps = {
      ...packageJson.dependencies,
      ...packageJson.devDependencies
    };
    if (deps.react) projectType = "React";
    else if (deps.vue) projectType = "Vue";
    else if (deps.angular) projectType = "Angular";
    else if (deps.express) projectType = "Node.js API";
    else if (deps.nextjs) projectType = "Next.js";
    if (deps.jest) detectedFrameworks.push("Jest");
    if (deps.vitest) detectedFrameworks.push("Vitest");
    if (deps.playwright) detectedFrameworks.push("Playwright");
    if (deps.eslint) detectedFrameworks.push("ESLint");
  } catch {
  }
  console.log(`\u{1F4E6} Detected project: ${chalk.cyan(projectType)}`);
  if (detectedFrameworks.length) {
    console.log(
      `\u{1F527} Detected tools: ${chalk.cyan(detectedFrameworks.join(", "))}`
    );
  }
  console.log("");
  const { proceed } = await inquirer.prompt([
    {
      type: "confirm",
      name: "proceed",
      message: "Continue with setup?",
      default: true
    }
  ]);
  if (!proceed) {
    console.log(chalk.gray("Setup cancelled"));
    return;
  }
  await configureQualityGates(projectRoot);
  const { enable } = await inquirer.prompt([
    {
      type: "confirm",
      name: "enable",
      message: "Enable quality gates now?",
      default: true
    }
  ]);
  if (enable) {
    const spinner = ora();
    await enableQualityGates(projectRoot, frameManager, db, spinner);
  }
  console.log(chalk.bold("\n\u{1F389} Setup Complete!\n"));
  console.log(
    "Quality gates will now run automatically after Claude completes tasks."
  );
  console.log("Check status with: stackmemory quality --status");
}
async function getProjectRoot() {
  return process.cwd();
}
async function loadConfig(projectRoot) {
  const configPath = path.join(projectRoot, ".stackmemory", "config.json");
  try {
    const content = await fs.readFile(configPath, "utf-8");
    return JSON.parse(content);
  } catch {
    return {};
  }
}
async function saveConfig(projectRoot, config) {
  const configPath = path.join(projectRoot, ".stackmemory", "config.json");
  await fs.mkdir(path.dirname(configPath), { recursive: true });
  await fs.writeFile(configPath, JSON.stringify(config, null, 2), "utf-8");
}
function getTestCommand(config) {
  if (config.testFrameworks?.testCommand) {
    return chalk.gray(`(${config.testFrameworks.testCommand})`);
  }
  return chalk.gray("(auto-detect)");
}
function getLintCommand(config) {
  if (config.testFrameworks?.lintCommand) {
    return chalk.gray(`(${config.testFrameworks.lintCommand})`);
  }
  return chalk.gray("(auto-detect)");
}
async function getRecentQualityResults(frameManager) {
  return [];
}
async function getRecentlyModifiedFiles(projectRoot) {
  try {
    const { execFileSync } = await import("child_process");
    const output = execFileSync("git", ["diff", "--name-only", "HEAD~1"], {
      cwd: projectRoot,
      encoding: "utf-8"
    });
    return output.trim().split("\n").filter((f) => f.length > 0);
  } catch {
    return [];
  }
}
async function createServiceFile(projectRoot) {
  const serviceContent = `# StackMemory Quality Gates Service
# This file indicates quality gates are enabled
# Created: ${(/* @__PURE__ */ new Date()).toISOString()}
`;
  const servicePath = path.join(projectRoot, ".stackmemory", "quality.service");
  await fs.writeFile(servicePath, serviceContent, "utf-8");
}
var quality_default = createQualityCommand();
export {
  createQualityCommand,
  quality_default as default
};
//# sourceMappingURL=quality.js.map
