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

const DEFAULT_ALIBABA_UPSTREAM = "https://dashscope.aliyuncs.com/compatible-mode/v1";

/**
 * Alibaba Provider Implementation (DashScope)
 */
export const alibabaProvider: ProviderProtocol = {
  name: "alibaba",

  matches(model: string): boolean {
    // Normalize: lowercase, replace whitespace with hyphens
    const m = model.toLowerCase().replace(/\s+/g, "-");
    // Match glm-5* and glm-5.1* models
    if (m.startsWith("glm-5")) {
      return true;
    }
    // Match qwen models (qwen3.6-plus, qwen3.7-max, Qwen3.6 Plus, etc.)
    if (m.startsWith("qwen")) {
      return true;
    }
    return false;
  },

  getUpstreamBase(_isChatCompletions: boolean, _providerConfig?: { baseUrl?: string }): string {
    return DEFAULT_ALIBABA_UPSTREAM;
  },

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

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