import { defineCommand, useLLM, findRepoRoot, useConfig, useLoader } from '@kb-labs/sdk';
import { getGitStatus, hasChanges, generateCommitPlan, savePlan, applyCommitPlan, saveToHistory, clearPlan, pushCommits } from '@kb-labs/commit-core';
import { commitEnv, resolveCommitConfig } from '@kb-labs/commit-contracts';
import * as path from 'path';

// src/cli/commands/run.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/run.ts
var run_default = defineCommand({
  id: "commit:commit",
  description: "Generate and apply commits (default flow)",
  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 dryRun = flags["dry-run"] ?? false;
      const withPush = flags["with-push"] ?? false;
      const outputJson = flags.json ?? false;
      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("Git status analyzed");
      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 })
      });
      await savePlan(cwd, plan);
      analyzeLoader.succeed(`Generated commit plan with ${plan.commits.length} commit(s)`);
      if (dryRun) {
        const commitsItems = plan.commits.map((commit) => {
          const scope = commit.scope ? `(${commit.scope})` : "";
          return `${commit.type}${scope}: ${commit.message} [${commit.files.length} file(s)]`;
        });
        const summaryItems = [
          `Files: ${plan.metadata.totalFiles}`,
          `Commits: ${plan.metadata.totalCommits}`,
          "Mode: Dry Run"
        ];
        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");
        }
        const timing = Date.now() - startTime;
        ctx.ui?.success?.("Plan generated (no commits created)", {
          title: "Git Commit (Dry Run)",
          sections: [
            { header: "Summary", items: summaryItems },
            { header: "Planned Commits", items: commitsItems }
          ],
          timing
        });
        return {
          exitCode: 0,
          result: {
            plan,
            applied: false,
            pushed: false,
            commits: plan.commits.map((c) => ({
              id: c.id,
              message: `${c.type}${c.scope ? `(${c.scope})` : ""}: ${c.message}`
            }))
          },
          meta: {
            timing
          }
        };
      }
      const applyLoader = useLoader("Applying commits...");
      applyLoader.start();
      const applyResult = await applyCommitPlan(scopeCwd, plan);
      if (!applyResult.success) {
        applyLoader.fail("Failed to apply commits");
        for (const error of applyResult.errors) {
          ctx.ui?.error?.(`  ${error}`);
        }
        return {
          exitCode: 1
        };
      }
      await saveToHistory(cwd, plan, applyResult);
      await clearPlan(cwd);
      applyLoader.succeed(`Applied ${applyResult.appliedCommits.length} commit(s)`);
      let pushed = false;
      if (withPush) {
        const pushLoader = useLoader("Pushing commits...");
        pushLoader.start();
        const pushResult = await pushCommits(scopeCwd);
        if (pushResult.success) {
          pushed = true;
          pushLoader.succeed(`Pushed to ${pushResult.remote}/${pushResult.branch}`);
        } else {
          pushLoader.fail(`Failed to push: ${pushResult.error}`);
        }
      }
      const output = {
        plan,
        applied: true,
        pushed,
        commits: applyResult.appliedCommits.map((c) => ({
          id: c.groupId,
          sha: c.sha,
          message: c.message
        }))
      };
      if (outputJson) {
        ctx.ui?.json?.(output);
      } else {
        const commitsItems = applyResult.appliedCommits.map((c) => {
          const shortSha = c.sha.substring(0, 7);
          const firstLine = c.message.split("\n")[0];
          return `[${shortSha}] ${firstLine}`;
        });
        const summaryItems = [
          `Commits: ${applyResult.appliedCommits.length}`,
          `Pushed: ${pushed ? "Yes" : "No"}`
        ];
        if (plan.metadata.llmUsed) {
          const llmPhase = plan.metadata.escalated ? "Phase 2" : "Phase 1";
          summaryItems.push(`LLM: ${llmPhase}`);
          if (plan.metadata.tokensUsed) {
            summaryItems.push(`Tokens: ${plan.metadata.tokensUsed}`);
          }
        }
        const timing = Date.now() - startTime;
        ctx.ui?.success?.("Commits created successfully", {
          title: "Git Commit",
          sections: [
            { header: "Summary", items: summaryItems },
            { header: "Commits Created", items: commitsItems }
          ],
          timing
        });
      }
      return {
        exitCode: 0,
        result: output,
        meta: {
          timing: Date.now() - startTime
        }
      };
    }
  }
});

export { run_default as default };
//# sourceMappingURL=run.js.map
//# sourceMappingURL=run.js.map