import type { CapturedLog } from "../../schemas";
import type { ProviderProtocol } from "../protocol";
import { registry } from "../providers";
import { extractAnthropicStream } from "./stream";

const DEFAULT_UPSTREAM = "https://api.anthropic.com";

// Default routes - MiniMax is hardcoded here
const DEFAULT_ROUTES: Record<string, string> = {
  MiniMax: "https://api.minimaxi.com/anthropic",
};

function getUpstreamForModel(model: string): string {
  let bestPrefix = "";
  let bestUrl = DEFAULT_UPSTREAM;

  for (const [prefix, url] of Object.entries(DEFAULT_ROUTES)) {
    if (model.startsWith(prefix) && prefix.length > bestPrefix.length) {
      bestPrefix = prefix;
      bestUrl = url;
    }
  }

  return bestUrl;
}

/**
 * Anthropic Provider Implementation
 */
export const anthropicProvider: ProviderProtocol = {
  name: "anthropic",

  matches(model: string): boolean {
    const modelLower = model.toLowerCase();

    // Don't match OpenAI models
    if (modelLower.startsWith("openai-")) {
      return false;
    }

    // Match Anthropic models
    if (modelLower.includes("claude") || modelLower.includes("anthropic")) {
      return true;
    }

    // Match known route prefixes (e.g., MiniMax)
    for (const prefix of Object.keys(DEFAULT_ROUTES)) {
      if (modelLower.startsWith(prefix.toLowerCase())) {
        return true;
      }
    }

    // Default to Anthropic for unknown models (legacy behavior)
    return true;
  },

  getUpstreamBase(_isChatCompletions: boolean, providerConfig?: { baseUrl?: string }): string {
    if (providerConfig?.baseUrl !== undefined) {
      return providerConfig.baseUrl;
    }
    return DEFAULT_UPSTREAM;
  },

  extractStream(
    raw: string,
    log: CapturedLog,
    fallbackModel?: string,
    collectChunks?: boolean,
  ): string {
    return extractAnthropicStream(raw, log, fallbackModel, collectChunks);
  },
};

// Register the provider
registry.register(anthropicProvider);
