import test from "node:test";
import assert from "node:assert/strict";

async function importLlmIntentModule() {
  const savedPromptUrl = process.env.PROMPT_SUPABASE_URL;
  const savedPromptKey = process.env.PROMPT_SUPABASE_SERVICE_ROLE_KEY;

  try {
    delete process.env.PROMPT_SUPABASE_URL;
    delete process.env.PROMPT_SUPABASE_SERVICE_ROLE_KEY;

    return await import(new URL(`../src/llm-intent.js?case=${Date.now()}-${Math.random()}`, import.meta.url).href);
  } finally {
    if (savedPromptUrl === undefined) {
      delete process.env.PROMPT_SUPABASE_URL;
    } else {
      process.env.PROMPT_SUPABASE_URL = savedPromptUrl;
    }

    if (savedPromptKey === undefined) {
      delete process.env.PROMPT_SUPABASE_SERVICE_ROLE_KEY;
    } else {
      process.env.PROMPT_SUPABASE_SERVICE_ROLE_KEY = savedPromptKey;
    }
  }
}

async function withEnv(overrides, fn) {
  const original = { ...process.env };
  process.env = { ...original, ...overrides };
  for (const [key, value] of Object.entries(overrides)) {
    if (value === undefined) {
      delete process.env[key];
    }
  }

  try {
    return await fn();
  } finally {
    process.env = original;
  }
}

test("buildSystemPrompt 在缺少 prompt store 配置时会报错", async () => {
  const intent = await importLlmIntentModule();
  await assert.rejects(() => intent.buildSystemPrompt(1), /PROMPT_SUPABASE_URL|PROMPT_SUPABASE_SERVICE_ROLE_KEY/);
});

test("buildGenericRoundSystemPrompt 会渲染 generic round 变量", async () => {
  const intent = await importLlmIntentModule();
  const prompt = intent.buildGenericRoundSystemPrompt(
    5,
    {
      name: "补充确认",
      templateText: "可以先打样吗？",
      passCondition: "商家确认支持打样",
    },
    "第 {{current_round}} 轮，本轮名称：{{round_name}}，话术：{{template_text}}，条件：{{pass_condition}}",
  );

  assert.match(prompt, /第 5 轮/);
  assert.match(prompt, /本轮名称：补充确认/);
  assert.match(prompt, /可以先打样吗？/);
  assert.match(prompt, /商家确认支持打样/);
});

test("resolveChatbotIntentModel 优先使用 CHATBOT_INTENT_LLM_MODEL 并兼容阶段默认", async () => {
  await withEnv({
    CHATBOT_INTENT_LLM_MODEL: "chatbot-intent-model",
    LLM_MODEL: "global-model",
  }, async () => {
    const intent = await importLlmIntentModule();
    assert.equal(intent.resolveChatbotIntentModel(), "chatbot-intent-model");
  });

  await withEnv({
    CHATBOT_INTENT_LLM_MODEL: "  ",
    LLM_MODEL: "global-model",
  }, async () => {
    const intent = await importLlmIntentModule();
    assert.equal(intent.resolveChatbotIntentModel(), "global-model");
  });

  await withEnv({
    CHATBOT_INTENT_LLM_MODEL: "",
    LLM_MODEL: "",
  }, async () => {
    const intent = await importLlmIntentModule();
    assert.equal(intent.resolveChatbotIntentModel(), "deepseek-v4-flash");
  });
});

test("Prompt scope 使用客服意图阶段最终模型", async () => {
  await withEnv({
    PROMPT_PROVIDER: "prompt-provider",
    LLM_PROVIDER: "global-provider",
    CHATBOT_INTENT_LLM_MODEL: "chatbot-intent-model",
    LLM_MODEL: "global-model",
  }, async () => {
    const intent = await importLlmIntentModule();
    assert.deepEqual(intent.getPromptScope(), {
      provider: "prompt-provider",
      model: "chatbot-intent-model",
    });
  });
});

test("callLLM 请求体使用客服意图阶段模型", async () => {
  await withEnv({
    LLM_API_KEY: "test-key",
    LLM_BASE_URL: "https://llm.example.test/v1/",
    CHATBOT_INTENT_LLM_MODEL: "chatbot-intent-model",
    LLM_MODEL: "global-model",
  }, async () => {
    const intent = await importLlmIntentModule();
    const originalFetch = globalThis.fetch;
    let capturedUrl = "";
    let capturedBody = {};
    globalThis.fetch = async (url, init) => {
      capturedUrl = String(url);
      capturedBody = JSON.parse(init.body);
      return {
        ok: true,
        json: async () => ({
          choices: [{ message: { content: "{\"passed\":true}" } }],
        }),
      };
    };

    try {
      const raw = await intent.callLLM("system", "user");
      assert.equal(raw, "{\"passed\":true}");
      assert.equal(capturedUrl, "https://llm.example.test/v1/chat/completions");
      assert.equal(capturedBody.model, "chatbot-intent-model");
    } finally {
      globalThis.fetch = originalFetch;
    }
  });
});
