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

// tools/fastapply/core.ts
import { join, resolve, relative } from "path";
var DEFAULT_CONFIG = {
  morphApiUrl: "https://api.morphllm.com",
  baseDir: process.cwd(),
  generateUdiff: true,
  autoWrite: true,
  timeout: 9e4,
  debug: false
};
var FastApplyClient = class {
  config;
  constructor(config = {}) {
    this.config = {
      morphApiKey: config.apiKey,
      morphApiUrl: DEFAULT_CONFIG.morphApiUrl,
      debug: config.debug,
      timeout: config.timeout || DEFAULT_CONFIG.timeout,
      retryConfig: config.retryConfig,
      generateUdiff: DEFAULT_CONFIG.generateUdiff,
      autoWrite: DEFAULT_CONFIG.autoWrite
    };
  }
  /**
   * Execute a file edit operation
   *
   * @param input - Edit parameters including filepath, instructions, and code_edit
   * @param overrides - Optional config overrides for this operation
   * @returns Edit result with success status and changes
   */
  async execute(input, overrides) {
    return executeEditFile(input, { ...this.config, ...overrides });
  }
  /**
   * Apply an edit to code directly without file I/O
   *
   * Useful for sandbox environments or when you manage your own file system.
   * Compatible with the earlier OpenAI client API contract.
   *
   * @param input - Code and edit parameters
   * @param overrides - Optional config overrides for this operation
   * @returns Result with merged code
   *
   * @example
   * ```typescript
   * const result = await client.applyEdit({
   *   originalCode: 'function hello() { return "world"; }',
   *   codeEdit: 'function hello() { return "universe"; }',
   *   instructions: 'Change return value'
   * });
   * console.log(result.mergedCode);
   * ```
   */
  async applyEdit(input, overrides) {
    const { applyEdit: applyEdit2 } = await import("./tools/fastapply/apply.js");
    return applyEdit2(input, { ...this.config, ...overrides });
  }
};
async function executeEditFile(input, config = {}) {
  const baseDir = config.baseDir || DEFAULT_CONFIG.baseDir;
  const fullPath = resolve(join(baseDir, input.target_filepath));
  logger.debug("FastApply", "execute_start", { target_filepath: input.target_filepath, baseDir, autoWrite: config.autoWrite !== false });
  const relativePath = relative(baseDir, fullPath);
  if (relativePath.startsWith("..") || fullPath === baseDir) {
    logger.warn("FastApply", "security_check_failed", { target_filepath: input.target_filepath, relative: relativePath });
    return {
      success: false,
      filepath: input.target_filepath,
      changes: { linesAdded: 0, linesRemoved: 0, linesModified: 0 },
      error: `Invalid filepath: '${input.target_filepath}' is outside baseDir`
    };
  }
  logger.debug("FastApply", "security_check", { resolved: fullPath, relative: relativePath });
  try {
    const { readFile, writeFile } = await import("fs/promises");
    const { callMorphAPI: callMorphAPI2, generateUdiff: generateUdiff2, countChanges: countChanges2 } = await import("./tools/fastapply/apply.js");
    let originalCode = "";
    let fileExists = true;
    try {
      originalCode = await readFile(fullPath, "utf-8");
      logger.debug("FastApply", "file_read", { path: fullPath, exists: true, size_bytes: originalCode.length });
    } catch (error) {
      if (error.code !== "ENOENT") {
        throw error;
      }
      fileExists = false;
      logger.debug("FastApply", "file_read", { path: fullPath, exists: false });
    }
    const instruction = input.instruction ?? input.instructions ?? "";
    logger.debug("FastApply", "api_call", { instruction_len: instruction.length, code_edit_len: input.code_edit.length, original_len: originalCode.length });
    const { content: mergedCode, completionId } = await callMorphAPI2(originalCode, input.code_edit, instruction, input.target_filepath, config);
    logger.debug("FastApply", "api_response", { completion_id: completionId, merged_len: mergedCode.length });
    const udiff = config.generateUdiff !== false ? generateUdiff2(originalCode, mergedCode, input.target_filepath) : void 0;
    if (config.autoWrite !== false) {
      await writeFile(fullPath, mergedCode, "utf-8");
      logger.debug("FastApply", "file_write", { path: fullPath, size_bytes: mergedCode.length });
    }
    const changes = countChanges2(originalCode, mergedCode);
    logger.debug("FastApply", "changes", { added: changes.linesAdded, removed: changes.linesRemoved, modified: changes.linesModified });
    return {
      success: true,
      filepath: input.target_filepath,
      udiff,
      changes,
      completionId
    };
  } catch (error) {
    const errorMessage = error instanceof Error ? error.message : "Unknown error occurred";
    logger.error("FastApply", "execute_error", { error: errorMessage, target_filepath: input.target_filepath, stack: error instanceof Error ? error.stack : void 0 });
    return {
      success: false,
      filepath: input.target_filepath,
      changes: { linesAdded: 0, linesRemoved: 0, linesModified: 0 },
      error: errorMessage
    };
  }
}

export {
  FastApplyClient,
  executeEditFile
};
//# sourceMappingURL=chunk-SFIMDGVL.js.map