package cmd

import (
	"bytes"
	"os"
	"path/filepath"
	"strings"
	"testing"

	"github.com/stretchr/testify/require"

	"github.com/tidbcloud/AgentTeam/desktop/internal/agent/runtimeconfig"
	"github.com/tidbcloud/AgentTeam/desktop/internal/daemon"
	"github.com/tidbcloud/AgentTeam/desktop/internal/profile"
)

func TestOnboardingDoesNotPromiseLocalDashboard(t *testing.T) {
	require.NotContains(t, strings.ToLower(onboardWelcomeDetail), "dashboard")
	require.Contains(t, strings.ToLower(onboardWelcomeDetail), "authenticated local api")
}

func TestDefaultOnboardServiceScope(t *testing.T) {
	require.Equal(t, daemon.ServiceScopeUser, defaultOnboardServiceScope("darwin", 1000))
	require.Equal(t, daemon.ServiceScopeSystem, defaultOnboardServiceScope("windows", 1000))
	require.Equal(t, daemon.ServiceScopeSystem, defaultOnboardServiceScope("linux", 0))
	require.Equal(t, daemon.ServiceScopeUser, defaultOnboardServiceScope("linux", 1000))
}

func TestPrintRuntimeDetectionStatusShowsUsableAndUnsupported(t *testing.T) {
	binDir := t.TempDir()
	opencodePath := writeOnboardRuntimeBinary(t, binDir, "opencode")
	writeOnboardBundledOpenCodeModels(t, opencodePath)
	codexPath := writeOnboardRuntimeBinary(t, binDir, "codex")
	t.Setenv("PATH", binDir)
	t.Setenv("HOME", t.TempDir())
	t.Setenv(profile.ConfigDirEnvKey, t.TempDir())
	t.Setenv("AGENTTEAM_MANAGED_OPENCODE_PATH", opencodePath)
	oldManagedVersion := runtimeconfig.ManagedOpenCodeVersion
	t.Cleanup(func() { runtimeconfig.ManagedOpenCodeVersion = oldManagedVersion })
	runtimeconfig.ManagedOpenCodeVersion = ""
	oldCodexProbe := runtimeconfig.CodexAppServerAvailable
	t.Cleanup(func() { runtimeconfig.CodexAppServerAvailable = oldCodexProbe })
	runtimeconfig.CodexAppServerAvailable = func(string) bool { return false }

	var output bytes.Buffer
	printRuntimeDetectionStatus(&output)

	text := output.String()
	require.Contains(t, text, "builtin: usable ("+opencodePath+")")
	require.Contains(t, text, "opencode: usable ("+opencodePath+")")
	require.Contains(t, text, "codex: unsupported ("+codexPath+")")
	require.Contains(t, text, "no longer installs or upgrades external runtimes")
	require.Contains(t, text, "Builtin OpenCode is shipped with AgentTeam Desktop")
	require.NotContains(t, text, "Select runtimes to auto-install")
}

func writeOnboardRuntimeBinary(t *testing.T, dir, name string) string {
	t.Helper()
	path := filepath.Join(dir, name)
	require.NoError(t, os.WriteFile(path, []byte("#!/bin/sh\nexit 0\n"), 0o755))
	return path
}

func writeOnboardBundledOpenCodeModels(t *testing.T, opencodePath string) {
	t.Helper()
	require.NoError(t, os.WriteFile(filepath.Join(filepath.Dir(opencodePath), "models.json"), []byte(`{"local":{"id":"local","name":"Local","env":[],"models":{}}}`+"\n"), 0o644))
}
