package dashboard

import (
	"encoding/json"
	"testing"

	"github.com/stretchr/testify/require"

	"github.com/tidbcloud/AgentTeam/desktop/internal/agent"
	"github.com/tidbcloud/AgentTeam/desktop/internal/api/dto"
	"github.com/tidbcloud/AgentTeam/desktop/internal/types"
)

type dashboardTestSessionStore struct {
	sessions []types.SessionSnapshot
}

func (s dashboardTestSessionStore) Sessions() []types.SessionSnapshot {
	return s.sessions
}

func TestRuntimeBundleAgentServerFieldsRemainSessionScoped(t *testing.T) {
	agents := []agent.Config{
		{ID: "active", Runtime: "codex", Source: agent.NewAgentTeamSource("agentteam-channel-1")},
		{ID: "idle", Runtime: "codex", Source: agent.NewAgentTeamSource("agentteam-channel-2")},
	}
	sessions := []types.SessionSnapshot{{
		AgentID:   "active",
		Status:    "running",
		ChannelID: "thr_123",
	}}
	summary := dto.RuntimeBundleSummary{}

	items := buildDashboardAgents(agents, sessions, dashboardRuntimeState{}, &summary)

	require.Len(t, items, 2)
	require.Equal(t, "thr_123", items[0].ServerID)
	require.Empty(t, items[1].ServerID)
}

func TestRuntimeBundleStatusSeparatesInstalledFromReady(t *testing.T) {
	runtimeResp := dto.RuntimeResponse{Name: "opencode", Type: "opencode", Binary: "opencode"}
	unsupported := dashboardRuntimeFromResponse(runtimeResp, map[string]dto.DetectRuntimeResponse{
		"opencode": {
			Type:       "opencode",
			Installed:  true,
			Capable:    false,
			ReasonCode: "capability_missing",
			Message:    "app-server unavailable",
		},
	}, 0, false)

	require.True(t, unsupported.Installed)
	require.False(t, unsupported.Ready)
	require.Equal(t, runtimeStatusUnsupported, unsupported.Status)
	require.Equal(t, "app-server unavailable", unsupported.Attention)

	body, err := json.Marshal(unsupported)
	require.NoError(t, err)
	require.Contains(t, string(body), `"ready":false`)
	require.Contains(t, string(body), `"installed":true`)

	ready := dashboardRuntimeFromResponse(runtimeResp, map[string]dto.DetectRuntimeResponse{
		"opencode": {
			Type:      "opencode",
			Installed: true,
			Capable:   true,
		},
	}, 0, false)
	require.False(t, ready.Configured)
	require.True(t, ready.Ready)
	require.Equal(t, runtimeStatusReady, ready.Status)
	require.Empty(t, ready.PrimaryAction)
}

func TestRuntimeBundleKeyKeepsBuiltinSeparate(t *testing.T) {
	require.Equal(t, "builtin", dashboardRuntimeKey("builtin"))
}
