import { defineHandler, useLogger, useLLM, useConfig } from '@kb-labs/sdk';
import { resolveCommitConfig } from '@kb-labs/commit-contracts';
import { getFileDiff, getGitStatus, getAllChangedFiles } from '@kb-labs/commit-core/analyzer';
import * as path from 'path';

// src/rest/handlers/summarize-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/summarize-handler.ts
var summarize_handler_default = defineHandler({
  async execute(ctx, input) {
    const logger = useLogger();
    const llm = useLLM();
    if (!llm) {
      throw new Error("LLM is not available. Please configure an LLM adapter.");
    }
    const { scope = "root", file } = input.body || {};
    logger.info("[summarize-handler] Request received", { scope, file });
    try {
      const fileConfig = await useConfig();
      const config = resolveCommitConfig(fileConfig ?? {});
      const scopeCwd = resolveScopePath(ctx.cwd, scope, config.scope?.scopes);
      logger.info("[summarize-handler] Resolved scope", { scope, scopeCwd });
      let prompt;
      if (file) {
        logger.info("[summarize-handler] Summarizing file", { file });
        const diffResult = await getFileDiff(scopeCwd, file);
        prompt = `Analyze this git diff and provide a concise summary of what changed in this file.

File: ${file}

Diff:
\`\`\`diff
${diffResult.diff}
\`\`\`

Provide a 2-3 sentence summary focusing on:
- What was added, modified, or removed
- The purpose/intent of the changes
- Any notable impacts

Keep it concise and technical.`;
      } else {
        logger.info("[summarize-handler] Summarizing all changes");
        const gitStatus = await getGitStatus(scopeCwd);
        const files = getAllChangedFiles(gitStatus);
        if (files.length === 0) {
          return {
            scope,
            summary: "No changes detected in this scope."
          };
        }
        const filesToSummarize = files.slice(0, 10);
        const diffs = await Promise.all(
          filesToSummarize.map(async (f) => {
            const diff = await getFileDiff(scopeCwd, f);
            return { file: f, diff: diff.diff, additions: diff.additions, deletions: diff.deletions };
          })
        );
        const diffsText = diffs.map((d) => `### ${d.file} (+${d.additions} -${d.deletions})
\`\`\`diff
${d.diff}
\`\`\``).join("\n\n");
        prompt = `Analyze these git diffs and provide a high-level summary of all changes in this scope.

Total files changed: ${files.length}
${files.length > 10 ? `(Showing first 10 files)` : ""}

${diffsText}

Provide a 3-5 sentence summary covering:
- Overall theme of the changes
- Key features added, bugs fixed, or refactorings done
- Any notable architectural changes

Keep it concise and at a high level.`;
      }
      logger.info("[summarize-handler] Calling LLM");
      const result = await llm.complete(prompt, {
        systemPrompt: "You are a technical code reviewer. Provide concise, accurate summaries of code changes.",
        temperature: 0.3,
        maxTokens: 500
      });
      logger.info("[summarize-handler] LLM response received", {
        tokensUsed: result.usage.promptTokens + result.usage.completionTokens
      });
      return {
        scope,
        file,
        summary: result.content.trim(),
        tokensUsed: result.usage.promptTokens + result.usage.completionTokens
      };
    } catch (error) {
      logger.error("[summarize-handler] Error", error);
      throw new Error(`Failed to summarize changes: ${error}`);
    }
  }
});

export { summarize_handler_default as default };
//# sourceMappingURL=summarize-handler.js.map
//# sourceMappingURL=summarize-handler.js.map