package agent

import (
	"context"

	"github.com/tidbcloud/AgentTeam/desktop/internal/agent/drivercontract"
	"github.com/tidbcloud/AgentTeam/desktop/internal/promptcompiler"
)

type testLaunchSurfaces = promptcompiler.TestLaunchSurfaces

func testLaunchConfig(cfg drivercontract.LaunchConfig, surfaces promptcompiler.TestLaunchSurfaces) drivercontract.LaunchConfig {
	runtime := string(cfg.RuntimeType)
	if runtime == "" {
		runtime = "test"
	}
	carrier, err := promptcompiler.NewTestLaunchCarrier(context.Background(), runtime, surfaces)
	if err != nil {
		panic(err)
	}
	cfg.CompiledPrompt = &carrier
	return cfg
}

func testRuntimeInput(text string) drivercontract.RuntimeInput {
	carrier, err := promptcompiler.NewTestDeliveryCarrier(context.Background(), "test", text)
	if err != nil {
		panic(err)
	}
	return drivercontract.RuntimeInput{CompiledPrompt: &carrier}
}

func testRuntimeInputWithConfig(cfg drivercontract.RuntimeInput, text string) drivercontract.RuntimeInput {
	carrier, err := promptcompiler.NewTestDeliveryCarrier(context.Background(), "test", text)
	if err != nil {
		panic(err)
	}
	cfg.CompiledPrompt = &carrier
	return cfg
}

func testLaunchSurface(cfg any, slot string) string {
	var carrier *promptcompiler.CompiledPrompt
	switch value := cfg.(type) {
	case drivercontract.LaunchConfig:
		carrier = value.CompiledPrompt
	case *drivercontract.LaunchConfig:
		if value != nil {
			carrier = value.CompiledPrompt
		}
	}
	if carrier == nil {
		return ""
	}
	return carrier.LaunchSurface(slot)
}

func setTestLaunchSurface(cfg *drivercontract.LaunchConfig, slot, value string) {
	if cfg == nil {
		return
	}
	var surfaces promptcompiler.TestLaunchSurfaces
	if cfg.CompiledPrompt != nil {
		surfaces = promptcompiler.TestLaunchSurfaces{
			Prompt: cfg.CompiledPrompt.LaunchSurface("prompt"), FreshPrompt: cfg.CompiledPrompt.LaunchSurface("freshPrompt"), ResumePrompt: cfg.CompiledPrompt.LaunchSurface("resumePrompt"),
			BaseInstructions: cfg.CompiledPrompt.LaunchSurface("baseInstructions"), DeveloperInstructions: cfg.CompiledPrompt.LaunchSurface("developerInstructions"), RuntimeCarrier: cfg.CompiledPrompt.LaunchSurface("runtimeCarrier"), ContractCarrierFile: cfg.CompiledPrompt.LaunchSurface("contractCarrierFile"),
		}
	}
	switch slot {
	case "Prompt":
		surfaces.Prompt = value
		if surfaces.FreshPrompt == "" {
			surfaces.FreshPrompt = value
		}
	case "FreshPrompt":
		surfaces.FreshPrompt = value
	case "ResumePrompt":
		surfaces.ResumePrompt = value
	case "BaseInstructions":
		surfaces.BaseInstructions = value
	case "DeveloperInstructions":
		surfaces.DeveloperInstructions = value
	case "ContractCarrierText":
		surfaces.RuntimeCarrier = value
	}
	runtime := string(cfg.RuntimeType)
	if runtime == "" {
		runtime = "test"
	}
	carrier, err := promptcompiler.NewTestLaunchCarrier(context.Background(), runtime, surfaces)
	if err != nil {
		panic(err)
	}
	cfg.CompiledPrompt = &carrier
}
