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

const DEFAULT_OPENAI_UPSTREAM = "https://api.openai.com/v1";

/**
 * OpenAI Provider Implementation
 */
export const openaiProvider: ProviderProtocol = {
  name: "openai",

  matches(model: string): boolean {
    const modelLower = model.toLowerCase();
    // Match OpenAI models
    if (modelLower.startsWith("openai-")) {
      return true;
    }
    // Also match common OpenAI model names
    if (
      modelLower.includes("gpt-") ||
      modelLower.includes("o1") ||
      modelLower.includes("o2") ||
      modelLower.includes("o3")
    ) {
      return true;
    }
    return false;
  },

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

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

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