package converter

import (
	"github.com/tidbcloud/AgentTeam/internal/api/dto"
	"github.com/tidbcloud/AgentTeam/internal/store/agent"
)

// ToAppAgents converts store app agents to API DTO app agents.
func ToAppAgents(agents []agent.AppAgent) []dto.AppAgent {
	if len(agents) == 0 {
		return []dto.AppAgent{}
	}
	items := make([]dto.AppAgent, 0, len(agents))
	for _, agent := range agents {
		items = append(items, ToAppAgent(agent))
	}
	return items
}

// ToAppAgent converts one store app agent to its API DTO shape.
func ToAppAgent(appAgent agent.AppAgent) dto.AppAgent {
	return dto.AppAgent{
		ID:                   appAgent.ID,
		Name:                 appAgent.Name,
		MemberID:             appAgent.MemberID,
		OwnerUserID:          appAgent.OwnerUserID,
		DisplayName:          appAgent.DisplayName,
		AvatarURL:            appAgent.AvatarURL,
		Description:          appAgent.Description,
		Runtime:              appAgent.Runtime,
		PermissionMode:       agent.DefaultAgentPermissionMode(appAgent.PermissionMode),
		Model:                appAgent.Model,
		ReasoningEffort:      appAgent.ReasoningEffort,
		LLMMode:              appAgent.LLMMode,
		BaseURL:              appAgent.BaseURL,
		Headers:              copyAgentHeaders(appAgent.Headers),
		WireAPI:              appAgent.WireAPI,
		APIKeyConfigured:     appAgent.APIKeyConfigured,
		LLMConfigError:       appAgent.LLMConfigError,
		ModelProfileID:       appAgent.ModelProfileID,
		MachineID:            appAgent.MachineID,
		MachineStatus:        appAgent.MachineStatus,
		SourceKind:           appAgent.SourceKind,
		SourceRef:            appAgent.SourceRef,
		CurrentRoleBinding:   toAgentRoleBindingSummary(appAgent.CurrentRoleBinding),
		CanManage:            appAgent.CanManage,
		CanReview:            appAgent.CanReview,
		CanDisable:           appAgent.CanDisable,
		AutoWakeEnabled:      appAgent.AutoWakeEnabled,
		Status:               appAgent.Status,
		Activity:             appAgent.Activity,
		ActivityDetail:       appAgent.ActivityDetail,
		CurrentInstance:      ToAppAgentInstance(appAgent.CurrentInstance),
		CreatedAt:            appAgent.CreatedAt,
		LatestRuntimeFailure: ToAgentRuntimeFailure(appAgent.LatestRuntimeFailure),
	}
}

func copyAgentHeaders(headers map[string]string) map[string]string {
	if len(headers) == 0 {
		return map[string]string{}
	}
	copied := make(map[string]string, len(headers))
	for key, value := range headers {
		copied[key] = value
	}
	return copied
}

// ToAppAgentInstance converts an optional store app agent instance to its API DTO shape.
func ToAppAgentInstance(instance *agent.AppAgentInstance) *dto.AppAgentInstance {
	if instance == nil {
		return nil
	}
	return &dto.AppAgentInstance{
		ID:             instance.ID,
		MachineID:      instance.MachineID,
		SessionID:      instance.SessionID,
		Status:         instance.Status,
		Activity:       instance.Activity,
		ActivityDetail: instance.ActivityDetail,
		SourceKind:     instance.SourceKind,
		SourceRef:      instance.SourceRef,
		StartedAt:      instance.StartedAt,
		LastSeenAt:     instance.LastSeenAt,
	}
}

// ToAgentRuntimeSnapshot converts one store runtime snapshot to its API DTO shape.
func ToAgentRuntimeSnapshot(snapshot agent.AgentRuntimeSnapshot) dto.AgentRuntimeSnapshot {
	return dto.AgentRuntimeSnapshot{
		AgentID:         snapshot.AgentID,
		MachineID:       snapshot.MachineID,
		MachineStatus:   snapshot.MachineStatus,
		AutoWakeEnabled: snapshot.AutoWakeEnabled,
		Status:          snapshot.Status,
		Activity:        snapshot.Activity,
		ActivityDetail:  snapshot.ActivityDetail,
		CurrentInstance: ToAppAgentInstance(snapshot.CurrentInstance),
	}
}

// ToAgentRuntimeSnapshots converts store runtime snapshots to API DTOs.
func ToAgentRuntimeSnapshots(snapshots []agent.AgentRuntimeSnapshot) []dto.AgentRuntimeSnapshot {
	if len(snapshots) == 0 {
		return []dto.AgentRuntimeSnapshot{}
	}
	items := make([]dto.AgentRuntimeSnapshot, 0, len(snapshots))
	for _, snapshot := range snapshots {
		items = append(items, ToAgentRuntimeSnapshot(snapshot))
	}
	return items
}

// ToAgentRuntimeFailure converts an optional store runtime failure summary to its API DTO shape.
func ToAgentRuntimeFailure(failure *agent.AgentRuntimeFailureSummary) *dto.AgentRuntimeFailureSummary {
	if failure == nil {
		return nil
	}
	return &dto.AgentRuntimeFailureSummary{
		EventClass: failure.EventClass,
		MessageID:  failure.MessageID,
		Summary:    failure.Summary,
		Detail:     failure.Detail,
		OccurredAt: failure.OccurredAt,
	}
}

func toAgentRoleBindingSummary(summary *agent.AgentRoleBindingSummary) *dto.AgentRoleBindingSummary {
	if summary == nil {
		return nil
	}
	return &dto.AgentRoleBindingSummary{
		BindingKind:           toBrowserRoleBindingKind(summary.BindingKind),
		RoleID:                summary.RoleID,
		RoleVersionID:         summary.RoleVersionID,
		SourcePresetRoleID:    summary.SourcePresetRoleID,
		SourcePresetVersionID: summary.SourcePresetVersionID,
		ActiveDefinitionPath:  summary.ActiveDefinitionPath,
		RealizationID:         summary.RealizationID,
	}
}

func toBrowserRoleBindingKind(kind string) string {
	switch kind {
	case "my_role":
		return "my-role"
	case "preset_derived":
		return "preset-derived"
	default:
		return kind
	}
}
