import {
  fetchWithRetry,
  withTimeout
} from "./chunk-4VWJFZVS.js";

// tools/fastapply/apply.ts
import { createTwoFilesPatch } from "diff";
var DEFAULT_API_URL = "https://api.morphllm.com";
var DEFAULT_TIMEOUT = 3e4;
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 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>`;
  if (debug) {
    console.log(`[FastApply] Calling ${apiUrl}/v1/chat/completions`);
    console.log(`[FastApply] File: ${filepath}, Instructions: ${instructions.slice(0, 60)}...`);
    console.log(`[FastApply] Original: ${originalCode.length} chars, Edit: ${codeEdit.length} chars`);
  }
  const startTime = Date.now();
  const fetchPromise = fetchWithRetry(
    `${apiUrl}/v1/chat/completions`,
    {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "Authorization": `Bearer ${apiKey}`
      },
      body: JSON.stringify({
        model: "morph-v3-fast",
        messages: [{ role: "user", content: message }]
      })
    },
    config.retryConfig
  );
  const response = await withTimeout(
    fetchPromise,
    timeout,
    `Morph API request timed out after ${timeout}ms`
  );
  if (!response.ok) {
    const error = await response.text();
    if (debug) console.error(`[FastApply] API error: ${response.status} - ${error}`);
    throw new Error(`Morph API error (${response.status}): ${error}`);
  }
  const data = await response.json();
  const elapsed = Date.now() - startTime;
  if (debug) {
    console.log(`[FastApply] \u2705 Success in ${elapsed}ms, merged: ${data.choices[0].message.content.length} chars`);
  }
  return data.choices[0].message.content;
}
async function applyEdit(input, config = {}) {
  const debug = config.debug || false;
  const filepath = input.filepath || "file";
  try {
    if (debug) {
      console.log(`[FastApply] Applying edit to code (${input.originalCode.length} chars)`);
    }
    const mergedCode = await callMorphAPI(
      input.originalCode,
      input.codeEdit,
      input.instructions,
      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
    };
  } catch (error) {
    const errorMessage = error instanceof Error ? error.message : "Unknown error occurred";
    if (debug) console.error(`[FastApply] Error: ${errorMessage}`);
    return {
      success: false,
      changes: { linesAdded: 0, linesRemoved: 0, linesModified: 0 },
      error: errorMessage
    };
  }
}

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