import { defineHandler, useConfig } from '@kb-labs/sdk';
import { resolveCommitConfig, COMMIT_CACHE_PREFIX } from '@kb-labs/commit-contracts';
import { generateCommitPlan } from '@kb-labs/commit-core/generator';
import { savePlan, getCurrentPlanPath } from '@kb-labs/commit-core/storage';
import { SecretsDetectedError } from '@kb-labs/commit-core/analyzer';
import * as path from 'path';

// src/rest/handlers/generate-handler.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/rest/handlers/generate-handler.ts
var generate_handler_default = defineHandler({
  async execute(ctx, input) {
    const { scope = "root", dryRun, allowSecrets = false, autoConfirm = false } = input.body ?? {};
    const startTime = Date.now();
    try {
      const fileConfig = await useConfig();
      const config = resolveCommitConfig(fileConfig ?? {});
      const scopeCwd = resolveScopePath(ctx.cwd, scope, config.scope?.scopes);
      const plan = await generateCommitPlan({
        cwd: scopeCwd,
        allowSecrets,
        autoConfirm,
        onProgress: (message) => {
        }
      });
      let planPath = "";
      if (!dryRun) {
        await savePlan(ctx.cwd, plan, scope);
        planPath = getCurrentPlanPath(ctx.cwd, scope);
        const appliedCacheKey = `${COMMIT_CACHE_PREFIX}plan-applied:${scope}`;
        await ctx.platform.cache.delete(appliedCacheKey);
      }
      if (ctx.platform.analytics) {
        await ctx.platform.analytics.track("commit.plan.generated", {
          scope,
          dryRun,
          filesChanged: plan.metadata.totalFiles,
          commitsGenerated: plan.metadata.totalCommits,
          llmUsed: plan.metadata.llmUsed,
          tokensUsed: plan.metadata.tokensUsed,
          escalated: plan.metadata.escalated,
          durationMs: Date.now() - startTime
        });
      }
      return {
        success: true,
        plan,
        planPath,
        scope,
        secretsDetected: false
      };
    } catch (error) {
      if (error instanceof SecretsDetectedError) {
        if (ctx.platform.analytics) {
          await ctx.platform.analytics.track("commit.secrets.detected", {
            scope,
            secretCount: error.secretMatches.length,
            durationMs: Date.now() - startTime
          });
        }
        return {
          success: false,
          scope,
          secretsDetected: true,
          secrets: error.secretMatches.map((match) => ({
            file: match.file,
            line: match.line,
            column: match.column,
            type: match.patternName,
            pattern: match.pattern,
            matched: match.matchedText,
            context: match.snippet
          })),
          message: error.message
        };
      }
      if (ctx.platform.analytics) {
        await ctx.platform.analytics.track("commit.plan.error", {
          scope,
          dryRun,
          error: error instanceof Error ? error.message : String(error),
          durationMs: Date.now() - startTime
        });
      }
      throw new Error(`Failed to generate commit plan: ${error}`);
    }
  }
});

export { generate_handler_default as default };
//# sourceMappingURL=generate-handler.js.map
//# sourceMappingURL=generate-handler.js.map