//go:build e2e

package e2e

import (
	"encoding/json"
	"net/http"
	"net/http/httptest"
	"testing"

	"github.com/gin-gonic/gin"
	"github.com/stretchr/testify/require"
)

func TestAPI_HelpDocsCurrentContent(t *testing.T) {
	router := setupAPI(t)
	expectedDocs := []string{
		"overview",
		"getting-started",
		"agents",
		"runtimes",
		"servers",
		"skills",
		"cli-reference",
	}

	for _, locale := range []string{"en", "zh"} {
		t.Run(locale+" list", func(t *testing.T) {
			require.ElementsMatch(t, expectedDocs, getHelpDocList(t, router, locale))
		})
	}

	enRuntimes := getHelpDocContent(t, router, "en", "runtimes")
	require.Contains(t, enRuntimes, "`codex` | `codex` | Codex app-server integration path")
	require.Contains(t, enRuntimes, "agentteam starts `codex app-server`")

	enAgents := getHelpDocContent(t, router, "en", "agents")
	require.Contains(t, enAgents, "memory/system/identity.md")
	require.Contains(t, enAgents, "4096")

	enServers := getHelpDocContent(t, router, "en", "servers")
	require.Contains(t, enServers, "AgentTeam server-selected agent IDs")
	require.Contains(t, enServers, "`default_agent`")

	enCLI := getHelpDocContent(t, router, "en", "cli-reference")
	require.NotContains(t, enCLI, "agentteam provider enable")
	require.NotContains(t, enCLI, "agentteam agent enable")
	require.NotContains(t, enCLI, "agentteam skill enable")
	require.NotContains(t, enCLI, "agentteam session")
	require.NotContains(t, enCLI, "agentteam task")

	zhRuntimes := getHelpDocContent(t, router, "zh", "runtimes")
	require.Contains(t, zhRuntimes, "`codex` | `codex` | Codex app-server 集成路径")
	require.Contains(t, zhRuntimes, "agentteam 会启动 `codex app-server`")

	zhServers := getHelpDocContent(t, router, "zh", "servers")
	require.Contains(t, zhServers, "AgentTeam server 指定的 Agent ID")
	require.Contains(t, zhServers, "`default_agent`")

	zhCLI := getHelpDocContent(t, router, "zh", "cli-reference")
	require.NotContains(t, zhCLI, "agentteam provider enable")
	require.NotContains(t, zhCLI, "agentteam agent enable")
	require.NotContains(t, zhCLI, "agentteam skill enable")
	require.NotContains(t, zhCLI, "agentteam session")
	require.NotContains(t, zhCLI, "agentteam task")
}

func getHelpDocList(t *testing.T, router *gin.Engine, locale string) []string {
	t.Helper()
	req := httptest.NewRequest(http.MethodGet, "/api/internal/help-docs?locale="+locale, nil)
	rec := httptest.NewRecorder()
	router.ServeHTTP(rec, req)
	require.Equal(t, http.StatusOK, rec.Code)

	var payload struct {
		Docs []string `json:"docs"`
	}
	require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &payload))
	return payload.Docs
}

func getHelpDocContent(t *testing.T, router *gin.Engine, locale, doc string) string {
	t.Helper()
	req := httptest.NewRequest(http.MethodGet, "/api/internal/help-docs?locale="+locale+"&doc="+doc, nil)
	rec := httptest.NewRecorder()
	router.ServeHTTP(rec, req)
	require.Equal(t, http.StatusOK, rec.Code)
	return rec.Body.String()
}
