import {
  logger
} from "./chunk-F3NCFNUX.js";
import {
  SDK_VERSION
} from "./chunk-S4Y6O7CT.js";

// tools/fastapply/apply.ts
import { createTwoFilesPatch } from "diff";
import OpenAI from "openai";
var DEFAULT_API_URL = "https://api.morphllm.com";
var DEFAULT_TIMEOUT = 9e4;
function generateUdiff(original, modified, filepath) {
  return createTwoFilesPatch(
    filepath,
    filepath,
    original,
    modified,
    "Original",
    "Modified"
  );
}
function countChanges(original, modified) {
  const diff = generateUdiff(original, modified, "file");
  const lines = diff.split("\n");
  let linesAdded = 0;
  let linesRemoved = 0;
  for (const line of lines) {
    if (line.startsWith("+") && !line.startsWith("+++")) {
      linesAdded++;
    } else if (line.startsWith("-") && !line.startsWith("---")) {
      linesRemoved++;
    }
  }
  const linesModified = Math.min(linesAdded, linesRemoved);
  return {
    linesAdded: linesAdded - linesModified,
    linesRemoved: linesRemoved - linesModified,
    linesModified
  };
}
async function callMorphAPI(originalCode, codeEdit, instructions, filepath, config) {
  const apiKey = config.morphApiKey || (typeof process !== "undefined" ? process.env?.MORPH_API_KEY : void 0);
  const apiUrl = config.morphApiUrl || DEFAULT_API_URL;
  const useLarge = config.large ?? (typeof process !== "undefined" ? process.env?.MORPH_LARGE_APPLY !== "false" : true);
  const model = useLarge ? "morph-v3-large" : "morph-v3-fast";
  const timeout = config.timeout || DEFAULT_TIMEOUT;
  const debug = config.debug || false;
  if (!apiKey) {
    throw new Error(
      "Morph API key not found. Set MORPH_API_KEY environment variable or pass morphApiKey in config."
    );
  }
  const message = `<instruction>${instructions}</instruction>
<code>${originalCode}</code>
<update>${codeEdit}</update>`;
  logger.debug("FastApply", "http_request", {
    url: `${apiUrl}/v1/chat/completions`,
    model,
    filepath,
    instruction_len: instructions.length,
    original_len: originalCode.length,
    code_edit_len: codeEdit.length
  });
  const startTime = Date.now();
  const client = new OpenAI({
    apiKey,
    baseURL: `${apiUrl}/v1`,
    timeout,
    maxRetries: config.retryConfig?.maxRetries ?? 3,
    defaultHeaders: { "X-Morph-SDK-Version": SDK_VERSION }
  });
  try {
    const completion = await client.chat.completions.create({
      model,
      messages: [{ role: "user", content: message }]
    });
    const content = completion.choices[0]?.message?.content;
    if (!content) {
      throw new Error("Morph API returned empty response");
    }
    const elapsed = Date.now() - startTime;
    logger.debug("FastApply", "http_response", { status: 200, completion_id: completion.id, content_len: content.length, latency_ms: elapsed });
    return { content, completionId: completion.id };
  } catch (error) {
    const elapsed = Date.now() - startTime;
    logger.error("FastApply", "http_error", {
      status: error?.status || error?.response?.status,
      error: error?.message,
      latency_ms: elapsed
    });
    throw error;
  }
}
async function applyEdit(input, config = {}) {
  const filepath = input.filepath || "file";
  try {
    logger.debug("FastApply", "apply_edit_start", { original_len: input.originalCode.length, code_edit_len: input.codeEdit.length });
    const instruction = input.instruction ?? input.instructions ?? "";
    const { content: mergedCode, completionId } = await callMorphAPI(
      input.originalCode,
      input.codeEdit,
      instruction,
      filepath,
      config
    );
    const udiff = config.generateUdiff !== false ? generateUdiff(input.originalCode, mergedCode, filepath) : void 0;
    const changes = countChanges(input.originalCode, mergedCode);
    return {
      success: true,
      mergedCode,
      udiff,
      changes,
      completionId
    };
  } catch (error) {
    const errorMessage = error instanceof Error ? error.message : "Unknown error occurred";
    logger.error("FastApply", "apply_edit_error", { error: errorMessage });
    return {
      success: false,
      changes: { linesAdded: 0, linesRemoved: 0, linesModified: 0 },
      error: errorMessage
    };
  }
}

export {
  generateUdiff,
  countChanges,
  callMorphAPI,
  applyEdit
};
//# sourceMappingURL=chunk-ONDFNZXC.js.map