import {
  fetchWithRetry,
  withTimeout
} from "./chunk-E6BQJL5D.js";
import {
  logger
} from "./chunk-F3NCFNUX.js";

// modelrouter/core.ts
var DEFAULT_CONFIG = {
  apiUrl: "https://api.morphllm.com",
  timeout: 5e3,
  // 5 seconds (responses typically <500ms)
  debug: false
};
var BaseRouter = class {
  config;
  provider;
  constructor(provider, config = {}) {
    this.provider = provider;
    this.config = {
      apiKey: config.apiKey,
      apiUrl: config.apiUrl || DEFAULT_CONFIG.apiUrl,
      timeout: config.timeout || DEFAULT_CONFIG.timeout,
      debug: config.debug || DEFAULT_CONFIG.debug,
      retryConfig: config.retryConfig
    };
  }
  /**
   * Select the optimal model for a given input and mode
   */
  async selectModel(input) {
    const mode = input.mode || "balanced";
    const apiKey = this.config.apiKey || (typeof process !== "undefined" ? process.env?.MORPH_API_KEY : void 0);
    if (!apiKey) {
      throw new Error(
        "Morph API key is required. Set MORPH_API_KEY environment variable or pass apiKey in config."
      );
    }
    const url = `${this.config.apiUrl}/v1/router/${this.provider}`;
    const payload = {
      input: input.input,
      mode
    };
    logger.debug("ModelRouter", "request", { provider: this.provider, mode, input_len: input.input.length, url });
    try {
      const fetchPromise = fetchWithRetry(
        url,
        {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
            Authorization: `Bearer ${apiKey}`
          },
          body: JSON.stringify(payload)
        },
        this.config.retryConfig
      );
      const response = await withTimeout(
        fetchPromise,
        this.config.timeout,
        `Router API request timed out after ${this.config.timeout}ms`
      );
      if (!response.ok) {
        const errorText = await response.text();
        throw new Error(
          `Router API error (${response.status}): ${errorText || response.statusText}`
        );
      }
      const apiResult = await response.json();
      const result = {
        model: apiResult.model
      };
      logger.debug("ModelRouter", "selected", { provider: this.provider, model: apiResult.model, confidence: apiResult.confidence });
      return result;
    } catch (error) {
      logger.error("ModelRouter", "error", { provider: this.provider, error: error instanceof Error ? error.message : String(error) });
      throw error;
    }
  }
};
var OpenAIRouter = class extends BaseRouter {
  constructor(config = {}) {
    super("openai", config);
  }
  /**
   * Select optimal GPT-5 model
   * 
   * @param input - User input and mode
   * @returns Selected model name (gpt-5-mini | gpt-5-low | gpt-5-medium | gpt-5-high)
   */
  async selectModel(input) {
    return super.selectModel(input);
  }
};
var AnthropicRouter = class extends BaseRouter {
  constructor(config = {}) {
    super("anthropic", config);
  }
  /**
   * Select optimal Claude model
   * 
   * @param input - User input and mode
   * @returns Selected model name (claude-4.5-haiku | claude-4.5-sonnet)
   */
  async selectModel(input) {
    return super.selectModel(input);
  }
};
var GeminiRouter = class extends BaseRouter {
  constructor(config = {}) {
    super("gemini", config);
  }
  /**
   * Select optimal Gemini model
   * 
   * @param input - User input and mode
   * @returns Selected model name (gemini-2.5-flash | gemini-2.5-pro)
   */
  async selectModel(input) {
    return super.selectModel(input);
  }
};
var RawRouter = class extends BaseRouter {
  constructor(config = {}) {
    super("raw", config);
  }
  /**
   * Get raw difficulty classification
   * 
   * @param input - User input and mode
   * @returns Raw difficulty (easy | medium | hard | needs_info)
   */
  async classify(input) {
    const mode = input.mode || "balanced";
    const apiKey = this.config.apiKey || (typeof process !== "undefined" ? process.env?.MORPH_API_KEY : void 0);
    if (!apiKey) {
      throw new Error(
        "Morph API key is required. Set MORPH_API_KEY environment variable or pass apiKey in config."
      );
    }
    const url = `${this.config.apiUrl}/v1/router/raw`;
    const payload = {
      input: input.input,
      mode
    };
    logger.debug("RawRouter", "request", { mode, input_len: input.input.length, url });
    try {
      const fetchPromise = fetchWithRetry(
        url,
        {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
            Authorization: `Bearer ${apiKey}`
          },
          body: JSON.stringify(payload)
        },
        this.config.retryConfig
      );
      const response = await withTimeout(
        fetchPromise,
        this.config.timeout,
        `Router API request timed out after ${this.config.timeout}ms`
      );
      if (!response.ok) {
        const errorText = await response.text();
        throw new Error(
          `Router API error (${response.status}): ${errorText || response.statusText}`
        );
      }
      const apiResult = await response.json();
      let difficulty;
      if (apiResult.difficulty === "") {
        difficulty = "medium";
      } else {
        difficulty = apiResult.difficulty || apiResult.model;
      }
      const result = {
        difficulty
      };
      logger.debug("RawRouter", "classified", { difficulty });
      return result;
    } catch (error) {
      logger.error("RawRouter", "error", { error: error instanceof Error ? error.message : String(error) });
      throw error;
    }
  }
};

export {
  OpenAIRouter,
  AnthropicRouter,
  GeminiRouter,
  RawRouter
};
//# sourceMappingURL=chunk-EV4HZQEJ.js.map