package ai_test

import (
	"context"
	"testing"

	"apps/backend/internal/module/ai"

	"github.com/stretchr/testify/require"
)

func TestST_03_ListModelsNonEmpty(t *testing.T) {
	list := ai.ModelsForProvider("xai")
	require.NotEmpty(t, list)
	list2 := ai.ModelsForProvider("opencode-go")
	require.NotEmpty(t, list2)
	// OpenCode Go 不是 OpenAI gpt-* 模型名
	require.NotContains(t, list2, "gpt-4o-mini")
	require.Contains(t, list2, "kimi-k2.6")
}

func TestSanitizeModelDoesNotForceUserChoice(t *testing.T) {
	// 會員選 deepseek 不應被改掉
	require.Equal(t, "deepseek-v4-flash", ai.SanitizeModel("opencode-go", "deepseek-v4-flash"))
	require.Equal(t, "glm-5.1", ai.SanitizeModel("opencode-go", "glm-5.1"))
	// 空模型才給 fallback（僅 UI 後備，執行路徑不應靠這個覆寫設定）
	require.NotEmpty(t, ai.SanitizeModel("opencode-go", ""))
}

func TestST_09_NoKeyFails(t *testing.T) {
	c := &ai.FakeClient{}
	_, err := c.Complete(context.Background(), "", "grok-3", "hi")
	require.Error(t, err)
	_, err = c.ListModels(context.Background(), "")
	require.Error(t, err)
}

func TestST_05_PlatformCallOk(t *testing.T) {
	c := &ai.FakeClient{}
	out, err := c.Complete(context.Background(), "platform-key", "grok-3", "hello")
	require.NoError(t, err)
	require.Contains(t, out, "hello")
}

func TestNormalizeProvider(t *testing.T) {
	require.Equal(t, ai.ProviderXAI, ai.NormalizeProvider("xai"))
	require.Equal(t, ai.ProviderOpenCodeGo, ai.NormalizeProvider("opencode-go"))
	require.Equal(t, ai.ProviderOpenCodeGo, ai.NormalizeProvider("opencode"))
}

func TestSystemPromptLanguage(t *testing.T) {
	zh := ai.SystemPromptForLanguage("zh-TW")
	require.Contains(t, zh, "繁體中文")
	// 不應綁產品客服人設，否則仿寫會變助手腔
	require.NotContains(t, zh, "Harbor Desk")
	require.NotContains(t, zh, "助手")
	en := ai.SystemPromptForLanguage("en")
	require.Contains(t, en, "English")
	require.NotContains(t, en, "Harbor Desk")
	require.Equal(t, "zh-TW", ai.PickLanguage("", "zh-TW,zh;q=0.9"))
	require.Equal(t, "en", ai.PickLanguage("en", "zh-TW"))
	ctx := ai.WithResponseLanguage(context.Background(), "en-US")
	require.Equal(t, "en", ai.ResponseLanguageFrom(ctx))
}

func TestInferScriptLanguage(t *testing.T) {
	require.Equal(t, "en", ai.InferScriptLanguage(
		"I talk like a tired millennial who overshares about coffee and rent. Low energy, dry humor.",
		"Sample: honestly the subway is a personality test at this point",
	))
	require.Equal(t, "zh-TW", ai.InferScriptLanguage(
		"語氣偏碎念、口語，會用「欸」「真的假的」這類台灣用語。",
		"範例：今天又被會議吸走三小時，下班只想躺平。",
	))
	require.Equal(t, "", ai.InferScriptLanguage("hi"))
}
