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;
    }
  }
}

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, /商家确认支持打样/);
});