import { defineCommand, useLLM, findRepoRoot, useConfig, useLoader, displayArtifacts } from '@kb-labs/sdk';
import { stat } from 'fs/promises';
import { getGitStatus, hasChanges, generateCommitPlan, savePlan, getCurrentPlanPath } from '@kb-labs/commit-core';
import { commitEnv, resolveCommitConfig } from '@kb-labs/commit-contracts';
import * as path from 'path';

// src/cli/commands/generate.ts
function resolveScopePath(baseCwd, scopeId = "root", scopes) {
  const scopeDef = scopes?.find((s) => s.id === scopeId);
  const relativePath = scopeDef?.path ?? (scopeId === "root" ? "." : scopeId);
  return relativePath === "." ? baseCwd : path.join(baseCwd, relativePath);
}

// src/cli/commands/generate.ts
var generate_default = defineCommand({
  id: "commit:generate",
  description: "Generate commit plan from git changes",
  handler: {
    async execute(ctx, input) {
      const startTime = Date.now();
      const llm = useLLM();
      const cwd = await findRepoRoot(ctx.cwd || process.cwd()) ?? process.cwd();
      const fileConfig = await useConfig();
      const env = commitEnv.parse(ctx.runtime);
      const config = resolveCommitConfig(fileConfig ?? {}, env);
      const flags = input.flags ?? input;
      const effectiveScope = flags.scope ?? config.scope?.default ?? "root";
      const scopeCwd = resolveScopePath(cwd, effectiveScope, config.scope?.scopes);
      const allowSecrets = flags["allow-secrets"] ?? false;
      const autoConfirm = flags.yes ?? false;
      const statusLoader = useLoader("Checking git status...");
      statusLoader.start();
      const status = await getGitStatus(scopeCwd);
      if (!hasChanges(status)) {
        statusLoader.stop();
        ctx.ui?.warn?.("No changes to commit");
        return {
          exitCode: 1
        };
      }
      statusLoader.succeed("Found changes to commit");
      const analyzeLoader = useLoader("Analyzing changes...");
      analyzeLoader.start();
      const llmComplete = llm && config.llm.enabled ? async (prompt, options) => {
        const result = await llm.complete(prompt, {
          ...options,
          temperature: options?.temperature ?? config.llm.temperature,
          maxTokens: options?.maxTokens ?? config.llm.maxTokens
        });
        return {
          content: result.content,
          tokensUsed: result.usage ? result.usage.promptTokens + result.usage.completionTokens : void 0
        };
      } : void 0;
      const plan = await generateCommitPlan({
        cwd: scopeCwd,
        llmComplete,
        config,
        allowSecrets,
        autoConfirm,
        onProgress: (message) => analyzeLoader.update({ text: message })
      });
      const saveLoader = useLoader("Saving plan...");
      saveLoader.start();
      await savePlan(cwd, plan, effectiveScope);
      const planPath = getCurrentPlanPath(cwd, effectiveScope);
      saveLoader.succeed("Plan saved");
      analyzeLoader.succeed(`Generated commit plan with ${plan.commits.length} commit(s)`);
      const output = {
        plan,
        planPath
      };
      if (input.json) {
        ctx.ui?.json?.(output);
      } else {
        const commitsItems = plan.commits.map((commit) => {
          const scope = commit.scope ? `(${commit.scope})` : "";
          return `${commit.type}${scope}: ${commit.message} [${commit.files.length} file(s)]`;
        });
        const artifacts = [];
        try {
          const planStats = await stat(planPath);
          artifacts.push({
            name: "Commit Plan",
            path: planPath,
            size: planStats.size,
            modified: planStats.mtime,
            description: "Generated commit plan in JSON format"
          });
        } catch {
        }
        const sections = [];
        if (commitsItems.length > 0) {
          sections.push({
            header: "Commits",
            items: commitsItems
          });
        }
        if (artifacts.length > 0) {
          const artifactsLines = displayArtifacts(artifacts, {
            showSize: true,
            showTime: true,
            showDescription: true,
            maxItems: 10,
            title: ""
          });
          sections.push({
            header: "Artifacts",
            items: artifactsLines
          });
        }
        const summaryItems = [
          `Files: ${plan.metadata.totalFiles}`,
          `Commits: ${plan.metadata.totalCommits}`
        ];
        if (plan.metadata.llmUsed) {
          const llmPhase = plan.metadata.escalated ? "Phase 2 (with diff)" : "Phase 1";
          summaryItems.push(`LLM: ${llmPhase}`);
          if (plan.metadata.tokensUsed) {
            summaryItems.push(`Tokens: ${plan.metadata.tokensUsed}`);
          }
        } else {
          summaryItems.push("Generator: Heuristics");
        }
        sections.unshift({
          header: "Summary",
          items: summaryItems
        });
        const timing = Date.now() - startTime;
        ctx.ui?.success?.("Plan generated and saved", {
          title: "Generate Commit Plan",
          sections,
          timing
        });
      }
      return {
        exitCode: 0,
        result: output,
        meta: {
          timing: Date.now() - startTime
        }
      };
    }
  }
});

export { generate_default as default };
//# sourceMappingURL=generate.js.map
//# sourceMappingURL=generate.js.map