import { defineCommand, findRepoRoot, useConfig, useLoader } from '@kb-labs/sdk';
import { loadPlan, applyCommitPlan, saveToHistory, clearPlan } from '@kb-labs/commit-core';
import { resolveCommitConfig } from '@kb-labs/commit-contracts';
import * as path from 'path';

// src/cli/commands/apply.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/apply.ts
var apply_default = defineCommand({
  id: "commit:apply",
  description: "Apply current commit plan",
  handler: {
    async execute(ctx, input) {
      const startTime = Date.now();
      const cwd = await findRepoRoot(ctx.cwd || process.cwd()) ?? process.cwd();
      const scope = input.scope ?? "root";
      const fileConfig = await useConfig();
      const config = resolveCommitConfig(fileConfig ?? {});
      const scopeCwd = resolveScopePath(cwd, scope, config.scope?.scopes);
      const loadLoader = useLoader("Loading commit plan...");
      loadLoader.start();
      const plan = await loadPlan(cwd, scope);
      if (!plan) {
        loadLoader.fail("No commit plan found");
        ctx.ui?.error?.("Run `kb commit:generate` first.");
        return {
          exitCode: 1
        };
      }
      if (plan.commits.length === 0) {
        loadLoader.stop();
        ctx.ui?.warn?.("Commit plan is empty. Nothing to apply.");
        return {
          exitCode: 0,
          result: {
            success: true,
            commits: [],
            errors: []
          },
          meta: {
            timing: Date.now() - startTime
          }
        };
      }
      loadLoader.succeed(`Loaded plan with ${plan.commits.length} commit(s)`);
      const applyLoader = useLoader(`Applying ${plan.commits.length} commit(s)...`);
      applyLoader.start();
      const result = await applyCommitPlan(scopeCwd, plan, {
        force: input.force
      });
      if (result.success) {
        await saveToHistory(cwd, plan, result, scope);
        await clearPlan(cwd, scope);
        applyLoader.succeed(`Applied ${result.appliedCommits.length} commit(s) successfully`);
      } else {
        applyLoader.fail("Failed to apply commits");
      }
      const output = {
        success: result.success,
        commits: result.appliedCommits.map((c) => ({
          id: c.groupId,
          sha: c.sha,
          message: c.message
        })),
        errors: result.errors
      };
      if (input.json) {
        ctx.ui?.json?.(output);
      } else {
        if (result.success) {
          const commitsItems = result.appliedCommits.map((commit) => {
            return `${commit.sha.substring(0, 7)} ${commit.message}`;
          });
          const sections = [];
          if (commitsItems.length > 0) {
            sections.push({
              header: "Applied Commits",
              items: commitsItems
            });
          }
          const summaryItems = [
            `Total commits: ${result.appliedCommits.length}`,
            "Status: \u2705 Success"
          ];
          sections.unshift({
            header: "Summary",
            items: summaryItems
          });
          const timing = Date.now() - startTime;
          ctx.ui?.success?.("Commits applied successfully", {
            title: "Apply Commit Plan",
            sections,
            timing
          });
        } else {
          const errorItems = result.errors.map((error) => error);
          const timing = Date.now() - startTime;
          ctx.ui?.error?.("Failed to apply commits", {
            title: "Apply Commit Plan",
            sections: [
              {
                header: "Summary",
                items: [`Total errors: ${result.errors.length}`]
              },
              {
                header: "Errors",
                items: errorItems
              }
            ],
            timing
          });
        }
      }
      return {
        exitCode: result.success ? 0 : 1,
        result: output,
        meta: {
          timing: Date.now() - startTime
        }
      };
    }
  }
});

export { apply_default as default };
//# sourceMappingURL=apply.js.map
//# sourceMappingURL=apply.js.map