package clients

import (
	"context"
	"os"
	"strings"
	"testing"
	"time"

	"github.com/easyai/easyai-ai-gateway/apps/api/internal/store"
)

// TestKelingLegacyV1LiveOmni is opt-in because it creates billable upstream
// video tasks. Credentials must only be supplied through local environment
// variables; the test never prints them.
func TestKelingLegacyV1LiveOmni(t *testing.T) {
	if strings.TrimSpace(os.Getenv("KELING_LIVE_TEST")) != "1" {
		t.Skip("set KELING_LIVE_TEST=1 to run billable Kling V1 integration tests")
	}
	baseURL := strings.TrimRight(strings.TrimSpace(os.Getenv("KELING_TEST_BASE_URL")), "/")
	accessKey := strings.TrimSpace(os.Getenv("KELING_TEST_ACCESS_KEY"))
	secretKey := strings.TrimSpace(os.Getenv("KELING_TEST_SECRET_KEY"))
	if baseURL == "" || accessKey == "" || secretKey == "" {
		t.Fatal("KELING_TEST_BASE_URL, KELING_TEST_ACCESS_KEY, and KELING_TEST_SECRET_KEY are required")
	}

	models := []string{"kling-video-o1", "kling-v3-omni"}
	if selected := strings.TrimSpace(os.Getenv("KELING_LIVE_TEST_MODELS")); selected != "" {
		models = strings.Split(selected, ",")
	}
	for _, model := range models {
		model = strings.TrimSpace(model)
		t.Run(model, func(t *testing.T) {
			duration := 3
			if model == "kling-video-o1" {
				duration = 5
			}
			ctx, cancel := context.WithTimeout(context.Background(), 15*time.Minute)
			defer cancel()
			response, err := (KelingClient{}).Run(ctx, Request{
				Kind:      "videos.generations",
				ModelType: "omni_video",
				Model:     model,
				Body: map[string]any{
					"prompt":       "清晨的湖面上，一只白色纸鹤缓慢飞过，镜头平稳推进",
					"duration":     duration,
					"aspect_ratio": "16:9",
					"resolution":   "720p",
					"sound":        "off",
				},
				Candidate: store.RuntimeModelCandidate{
					BaseURL:           baseURL,
					Provider:          "keling",
					AuthType:          "AccessKey-SecretKey",
					ProviderModelName: model,
					Credentials: map[string]any{
						"accessKey": accessKey,
						"secretKey": secretKey,
					},
					Capabilities: map[string]any{"omni_video": map[string]any{}},
					PlatformConfig: map[string]any{
						"kelingPollIntervalMs":     5000,
						"kelingPollTimeoutSeconds": 840,
					},
				},
			})
			if err != nil {
				t.Fatalf("Kling V1 %s live task failed: %v", model, err)
			}
			items, _ := response.Result["data"].([]any)
			if len(items) == 0 {
				t.Fatalf("Kling V1 %s returned no video", model)
			}
			item, _ := items[0].(map[string]any)
			if strings.TrimSpace(stringFromAny(item["url"])) == "" {
				t.Fatalf("Kling V1 %s returned an empty video URL", model)
			}
			if strings.TrimSpace(response.RequestID) == "" {
				t.Fatalf("Kling V1 %s returned an empty request id", model)
			}
		})
	}
}
