import { afterEach, describe, expect, it } from "vitest";

import {
  resolveDocumentExtractionModel,
  resolveDocumentOcrModel,
} from "../standardization/document-extraction-llm.ts";
import { resolveSearchVisionModel } from "../playwright/search-vision-model.js";
import { resolveChatbotIntentModel } from "../../chatbot/src/llm-intent.js";
import { loadEnv, resetEnvCacheForTesting } from "./env.ts";
import { resolveLlmProvider, resolveStageLlmModel } from "./llm-client.ts";

const originalEnv = { ...process.env };
const minimalValidEnv: NodeJS.ProcessEnv = {
  SUPABASE_URL: "https://example.supabase.co",
  SUPABASE_SERVICE_ROLE_KEY: "service-role-key",
};

afterEach(() => {
  process.env = { ...originalEnv };
  resetEnvCacheForTesting();
});

describe("LLM stage regression matrix", () => {
  it("covers stage defaults and DeepSeek provider detection", () => {
    const env = loadEnv({
      ...minimalValidEnv,
      STANDARDIZATION_LLM_MODEL: "standardization-stage-model",
    });

    expect(resolveStageLlmModel("standardization", { env })).toBe("standardization-stage-model");
    expect(resolveStageLlmModel("keyword_semantic", { env })).toBe("deepseek-v4-flash");
    expect(resolveStageLlmModel("chatbot_intent", { env })).toBe("mimo-v2.5");
    expect(resolveLlmProvider({
      provider: "env",
      baseURL: "https://api.deepseek.com",
      model: "deepseek-v4-pro",
    })).toBe("deepseek");
    expect(resolveLlmProvider({
      provider: "env",
      baseURL: "https://api.xiaomimimo.com/v1",
      model: "mimo-v2.5",
    })).toBe("mimo");
  });

  it("keeps document OCR and extraction models independently configurable", () => {
    process.env = {
      ...originalEnv,
      ...minimalValidEnv,
      DOCUMENT_OCR_LLM_MODEL: "document-ocr-stage-model",
      DOCUMENT_EXTRACTION_LLM_MODEL: "document-extraction-stage-model",
    };
    resetEnvCacheForTesting();

    expect(resolveDocumentOcrModel()).toBe("document-ocr-stage-model");
    expect(resolveDocumentExtractionModel()).toBe("document-extraction-stage-model");
  });

  it("keeps search vision alias compatibility below the new stage env", () => {
    expect(resolveSearchVisionModel({
      SEARCH_VISION_LLM_MODEL: "search-stage-model",
      SEARCH_VISION_MODEL: "legacy-search-model",
    })).toBe("search-stage-model");
    expect(resolveSearchVisionModel({
      SEARCH_VISION_MODEL: "legacy-search-model",
    })).toBe("legacy-search-model");
  });

  it("keeps chatbot intent independent from automation stage models", () => {
    expect(resolveChatbotIntentModel({
      CHATBOT_INTENT_LLM_MODEL: "chatbot-intent-stage-model",
      STANDARDIZATION_LLM_MODEL: "standardization-stage-model",
      SEARCH_VISION_LLM_MODEL: "search-stage-model",
    })).toBe("chatbot-intent-stage-model");
  });
});
