package oci

import (
	"testing"
	"time"

	"github.com/oracle/oci-go-sdk/v65/common"
	"github.com/oracle/oci-go-sdk/v65/generativeai"
)

func TestToGenAiModelRetiredFilter(t *testing.T) {
	now := time.Date(2026, 7, 9, 0, 0, 0, 0, time.UTC)
	past := common.SDKTime{Time: now.Add(-24 * time.Hour)}
	future := common.SDKTime{Time: now.Add(30 * 24 * time.Hour)}
	chat := []generativeai.ModelCapabilityEnum{generativeai.ModelCapabilityChat}
	base := generativeai.ModelSummary{
		Id: common.String("ocid1..m"), DisplayName: common.String("meta.llama-x"),
		Vendor: common.String("meta"), Capabilities: chat,
		LifecycleState: generativeai.ModelLifecycleStateActive,
	}

	// 已过按需退役时间:不入池(ListModels 仍返回且 state ACTIVE,调用必 404)
	retired := base
	retired.TimeOnDemandRetired = &past
	if _, ok := toGenAiModel(retired, now); ok {
		t.Error("已退役模型应被剔除")
	}
	// 退役时间在未来:入池并携带弃用/退役时间
	upcoming := base
	upcoming.TimeDeprecated = &past
	upcoming.TimeOnDemandRetired = &future
	gm, ok := toGenAiModel(upcoming, now)
	if !ok || gm.Retired == nil || !gm.Retired.Equal(future.Time) || gm.Deprecated == nil {
		t.Fatalf("未退役模型应入池并带时间: ok=%v %+v", ok, gm)
	}
	// 未宣布任何时间:正常入池
	if _, ok := toGenAiModel(base, now); !ok {
		t.Error("正常模型应入池")
	}
}

func TestDedupGenAiModelsFineTunePreference(t *testing.T) {
	now := time.Date(2026, 7, 10, 0, 0, 0, 0, time.UTC)
	chat := []generativeai.ModelCapabilityEnum{generativeai.ModelCapabilityChat}
	chatFT := []generativeai.ModelCapabilityEnum{generativeai.ModelCapabilityChat, generativeai.ModelCapabilityFineTune}
	mk := func(id, name string, caps []generativeai.ModelCapabilityEnum) generativeai.ModelSummary {
		return generativeai.ModelSummary{
			Id: common.String(id), DisplayName: common.String(name), Vendor: common.String("meta"),
			Capabilities: caps, LifecycleState: generativeai.ModelLifecycleStateActive,
		}
	}
	const name = "meta.llama-3-70b-instruct"
	tests := []struct {
		name  string
		items []generativeai.ModelSummary
		want  string // 期望保留的 OCID
	}{
		{"基座在前、纯对话在后:保留纯对话条目", []generativeai.ModelSummary{mk("o-ft", name, chatFT), mk("o-od", name, chat)}, "o-od"},
		{"纯对话在前、基座在后:保留纯对话条目", []generativeai.ModelSummary{mk("o-od", name, chat), mk("o-ft", name, chatFT)}, "o-od"},
		{"仅基座条目:保留不误删", []generativeai.ModelSummary{mk("o-ft", name, chatFT)}, "o-ft"},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			got := dedupGenAiModels(tt.items, now)
			if len(got) != 1 || got[0].Ocid != tt.want {
				t.Errorf("dedupGenAiModels() = %+v, want 仅保留 %s", got, tt.want)
			}
		})
	}
}
