package modelid

import (
	"strings"
	"testing"

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

func TestParseUnifiedModelID_StandardFormat(t *testing.T) {
	providerID, modelName, err := ParseUnifiedModelID("openai/gpt-4")
	assert.NoError(t, err)
	assert.Equal(t, "openai", providerID)
	assert.Equal(t, "gpt-4", modelName)
}

func TestParseUnifiedModelID_ModelNameWithSlashes(t *testing.T) {
	providerID, modelName, err := ParseUnifiedModelID("azure/accounts/org-123/models/gpt-4")
	assert.NoError(t, err)
	assert.Equal(t, "azure", providerID)
	assert.Equal(t, "accounts/org-123/models/gpt-4", modelName)
}

func TestParseUnifiedModelID_MissingSeparator(t *testing.T) {
	_, _, err := ParseUnifiedModelID("gpt-4")
	assert.Error(t, err)
}

func TestParseUnifiedModelID_EmptyString(t *testing.T) {
	_, _, err := ParseUnifiedModelID("")
	assert.Error(t, err)
}

func TestParseUnifiedModelID_OnlySeparator(t *testing.T) {
	tests := []string{"/model", "provider/", "/"}
	for _, tc := range tests {
		_, _, err := ParseUnifiedModelID(tc)
		assert.Error(t, err, "输入 %q 应返回错误", tc)
	}
}

func TestParseUnifiedModelID_InvalidProviderID(t *testing.T) {
	tests := []string{
		"open-ai/gpt-4",
		"open.ai/gpt-4",
		"供应商/gpt-4",
		"open ai/gpt-4",
	}
	for _, tc := range tests {
		_, _, err := ParseUnifiedModelID(tc)
		assert.Error(t, err, "providerID 含非法字符 %q 应返回错误", tc)
	}
}

func TestFormatUnifiedModelID(t *testing.T) {
	assert.Equal(t, "openai/gpt-4", FormatUnifiedModelID("openai", "gpt-4"))
	assert.Equal(t, "anthropic/claude-3-opus", FormatUnifiedModelID("anthropic", "claude-3-opus"))
}

func TestValidateProviderID_Valid(t *testing.T) {
	validIDs := []string{"openai", "deep_seek", "provider01", "OpenAI"}
	for _, id := range validIDs {
		assert.NoError(t, ValidateProviderID(id), "%q 应校验通过", id)
	}
}

func TestValidateProviderID_InvalidChars(t *testing.T) {
	invalidIDs := []string{"open-ai", "open.ai", "open ai", "供应商", "open/ai"}
	for _, id := range invalidIDs {
		assert.Error(t, ValidateProviderID(id), "%q 应校验失败", id)
	}
}

func TestValidateProviderID_Empty(t *testing.T) {
	assert.Error(t, ValidateProviderID(""))
}

func TestValidateProviderID_TooLong(t *testing.T) {
	longID := strings.Repeat("a", 65)
	assert.Error(t, ValidateProviderID(longID))

	exactly64 := strings.Repeat("a", 64)
	assert.NoError(t, ValidateProviderID(exactly64))
}

func TestIsValidUnifiedModelID(t *testing.T) {
	assert.True(t, IsValidUnifiedModelID("openai/gpt-4"))
	assert.True(t, IsValidUnifiedModelID("anthropic/claude-3-opus-20240229"))
	assert.True(t, IsValidUnifiedModelID("azure/accounts/org/models/gpt-4"))

	assert.False(t, IsValidUnifiedModelID(""))
	assert.False(t, IsValidUnifiedModelID("gpt-4"))
	assert.False(t, IsValidUnifiedModelID("open-ai/gpt-4"))
	assert.False(t, IsValidUnifiedModelID("/model"))
	assert.False(t, IsValidUnifiedModelID("provider/"))
}
