import { defineHandler, useLogger, useConfig } from '@kb-labs/sdk';
import { resolveCommitConfig } from '@kb-labs/commit-contracts';
import { getFileDiff } from '@kb-labs/commit-core/analyzer';
import * as path from 'path';
import { join } from 'path';
import { readFile } from 'fs/promises';

// src/rest/handlers/diff-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);
}
var diff_handler_default = defineHandler({
  async execute(ctx, input) {
    const logger = useLogger();
    const scope = input.query?.scope || "root";
    const file = input.query?.file;
    logger.info("[diff-handler] Request received", { scope, file });
    if (!file) {
      throw new Error("File path is required");
    }
    try {
      const fileConfig = await useConfig();
      const config = resolveCommitConfig(fileConfig ?? {});
      const scopeCwd = resolveScopePath(ctx.cwd, scope, config.scope?.scopes);
      logger.info("[diff-handler] Resolved scope", { scope, scopeCwd });
      logger.info("[diff-handler] Calling getFileDiff", { cwd: scopeCwd, file });
      const result = await getFileDiff(scopeCwd, file);
      if (!result.diff || result.diff.trim().length === 0) {
        try {
          const absolutePath = join(scopeCwd, file);
          const content = await readFile(absolutePath, "utf-8");
          const additions = content.length === 0 ? 0 : content.split("\n").length;
          return {
            scope,
            file,
            diff: content,
            additions,
            deletions: 0
          };
        } catch (readError) {
          logger.warn("[diff-handler] Failed to read file content fallback", {
            file,
            error: readError instanceof Error ? readError.message : String(readError)
          });
        }
      }
      return {
        scope,
        file,
        diff: result.diff,
        additions: result.additions,
        deletions: result.deletions
      };
    } catch (error) {
      throw new Error(`Failed to get diff for file: ${error}`);
    }
  }
});

export { diff_handler_default as default };
//# sourceMappingURL=diff-handler.js.map
//# sourceMappingURL=diff-handler.js.map