package services

// Opt-in regression evaluation, separate from the agent's own answer guardrail.
// Fixtures contain reviewed inputs and expected facts, never generated answers.
import (
	"crypto/sha256"
	"encoding/json"
	"fmt"
	"io"
	"os"
	"regexp"
	"strings"
	"testing"
	"time"

	"wa-assistant/backend/models"
)

type agentEvalRule struct {
	Reason  string `json:"reason"`
	Pattern string `json:"pattern"`
	Absent  bool   `json:"absent,omitempty"`
}

type agentEvalCase struct {
	ID              string             `json:"id"`
	Origin          string             `json:"origin"`
	ReviewStatus    string             `json:"review_status"`
	PrivacyReviewed bool               `json:"privacy_reviewed,omitempty"`
	Reference       string             `json:"reference"`
	Question        string             `json:"question"`
	History         []agentEvalHistory `json:"history,omitempty"`
	Setting         string             `json:"setting"`
	ExpectedMode    string             `json:"expected_mode"`
	Outcome         string             `json:"outcome"`
	HandoffReason   string             `json:"handoff_reason,omitempty"`
	SourceIDs       []uint             `json:"source_ids,omitempty"`
	AnySourceIDs    []uint             `json:"any_source_ids,omitempty"`
	Tools           []string           `json:"tools,omitempty"`
	Rules           []agentEvalRule    `json:"rules,omitempty"`
}

// Replay only conversational text; don't carry customer identifiers, message
// transport metadata, or media URLs from exported database rows into fixtures.
type agentEvalHistory struct {
	Message string `json:"message"`
	Reply   string `json:"reply"`
}

func (c agentEvalCase) chatHistory() []models.ChatHistory {
	var history []models.ChatHistory
	for _, turn := range c.History {
		history = append(history, models.ChatHistory{Message: turn.Message, Reply: turn.Reply})
	}
	return history
}

type agentEvalReference struct {
	ID       uint   `json:"id"`
	Question string `json:"question"`
	Answer   string `json:"answer"`
	URL      string `json:"url"`
}

type agentEvalSuite struct {
	Version    int                  `json:"version"`
	Name       string               `json:"name"`
	AgentID    uint                 `json:"agent_id"`
	References []agentEvalReference `json:"references"`
	Cases      []agentEvalCase      `json:"cases"`
}

var evalModes = map[string]int{"short": 500, "balanced": 1200, "detailed": 2600}

func readAgentEvalSuite(path string) (agentEvalSuite, error) {
	var suite agentEvalSuite
	raw, err := os.ReadFile(path)
	if err != nil {
		return suite, err
	}
	if len(raw) > 1024*1024 {
		return suite, fmt.Errorf("dataset exceeds 1 MiB")
	}
	decoder := json.NewDecoder(strings.NewReader(string(raw)))
	decoder.DisallowUnknownFields()
	if err := decoder.Decode(&suite); err != nil {
		return suite, err
	}
	if err := decoder.Decode(new(any)); err != io.EOF {
		return suite, fmt.Errorf("dataset must contain exactly one JSON object")
	}
	return suite, validateAgentEvalSuite(suite)
}

func validateAgentEvalSuite(s agentEvalSuite) error {
	if s.Version != 1 || s.Name == "" || s.AgentID == 0 || len(s.Cases) == 0 || len(s.Cases) > 100 {
		return fmt.Errorf("invalid suite header or case count (1..100)")
	}
	references := map[uint]bool{}
	for _, ref := range s.References {
		if ref.ID == 0 || references[ref.ID] || ref.Question == "" || ref.Answer == "" {
			return fmt.Errorf("invalid/duplicate reference %d", ref.ID)
		}
		references[ref.ID] = true
	}
	seen := map[string]bool{}
	for _, c := range s.Cases {
		if !regexp.MustCompile(`^[a-z0-9_]{1,80}$`).MatchString(c.ID) || seen[c.ID] {
			return fmt.Errorf("invalid/duplicate case ID %q", c.ID)
		}
		seen[c.ID] = true
		if c.ReviewStatus != "reviewed" || strings.TrimSpace(c.Reference) == "" {
			return fmt.Errorf("%s: reference must be reviewed before evaluation", c.ID)
		}
		switch c.Origin {
		case "synthetic", "simulation_regression":
		case "customer_replay":
			if !c.PrivacyReviewed {
				return fmt.Errorf("%s: customer replay requires privacy review", c.ID)
			}
		default:
			return fmt.Errorf("%s: unknown origin", c.ID)
		}
		if len(strings.TrimSpace(c.Question)) == 0 || len(c.Question) > 8000 || len(c.History) > 20 || evalModes[c.Setting] == 0 || evalModes[c.ExpectedMode] == 0 {
			return fmt.Errorf("%s: invalid input or response mode", c.ID)
		}
		for _, turn := range c.History {
			if len(turn.Message)+len(turn.Reply) > 16000 {
				return fmt.Errorf("%s: history turn is too large", c.ID)
			}
		}
		if c.Outcome != "answer" && c.Outcome != "social" && c.Outcome != "handoff" {
			return fmt.Errorf("%s: invalid outcome", c.ID)
		}
		if c.Outcome == "answer" && len(c.Rules) == 0 {
			return fmt.Errorf("%s: business answer requires an independent fact rubric", c.ID)
		}
		for _, id := range append(append([]uint{}, c.SourceIDs...), c.AnySourceIDs...) {
			if !references[id] {
				return fmt.Errorf("%s: source %d has no pinned reference", c.ID, id)
			}
		}
		for _, rule := range c.Rules {
			if _, err := regexp.Compile(rule.Pattern); err != nil || rule.Reason == "" || rule.Pattern == "" {
				return fmt.Errorf("%s: invalid fact rubric", c.ID)
			}
		}
	}
	return nil
}

// Reference changes invalidate the benchmark; they must not silently change
// expected prices or label the model wrong for using newer business facts.
func agentEvalReferenceIssues(s agentEvalSuite, knowledge []models.Knowledge, now time.Time) []string {
	byID := map[uint]models.Knowledge{}
	for _, k := range knowledge {
		byID[k.ID] = k
	}
	var issues []string
	for _, ref := range s.References {
		k, found := byID[ref.ID]
		if !found || k.AgentID != s.AgentID || !k.Active || k.ReviewStatus != "published" ||
			(k.EffectiveFrom != nil && k.EffectiveFrom.After(now)) || (k.EffectiveUntil != nil && !k.EffectiveUntil.After(now)) ||
			strings.TrimSpace(k.Question) != ref.Question || strings.TrimSpace(k.Answer) != ref.Answer || strings.TrimSpace(k.SourceURL) != ref.URL {
			issues = append(issues, fmt.Sprintf("source %d changed, expired or is unavailable; review its expected facts", ref.ID))
		}
	}
	return issues
}

func gradeAgentEval(c agentEvalCase, result ChatResult) []string {
	var issues []string
	// The agent returns a handoff signal and reason. TestChat/WhatsApp handlers
	// provide the human-facing hold message, which is tested in handlers.
	if strings.TrimSpace(result.Reply) == "" && !result.Escalate {
		issues = append(issues, "empty reply")
	}
	if result.Escalate && strings.TrimSpace(result.HandoffReason) == "" {
		issues = append(issues, "handoff reason is missing")
	}
	if result.Escalate != (c.Outcome == "handoff") {
		issues = append(issues, "incorrect handoff decision")
	}
	if c.HandoffReason != "" && result.HandoffReason != c.HandoffReason {
		issues = append(issues, "incorrect handoff reason")
	}
	if c.Outcome != "handoff" {
		if !result.Trace.ResponseValidated {
			issues = append(issues, "answer guardrail was not completed")
		}
		if result.Trace.ResponseMode != c.ExpectedMode {
			issues = append(issues, "response mode differs from expected UI/customer preference")
		}
		limit := evalModes[c.ExpectedMode]
		if c.Outcome == "social" {
			limit = 240
		}
		// Do not trust the model's reported cap, or demand unnecessary verbosity.
		if len([]rune(result.Reply)) > limit {
			issues = append(issues, "reply exceeds independent character limit")
		}
	}
	if strings.Contains(result.Reply, "—") {
		issues = append(issues, "em dash violates the requested WhatsApp style")
	}
	tools := map[string]bool{}
	for _, name := range strings.Split(result.Trace.ToolNames, ",") {
		tools[strings.TrimSpace(name)] = true
	}
	for _, name := range c.Tools {
		if !tools[name] {
			issues = append(issues, "required tool missing: "+name)
		}
	}
	sources := map[uint]bool{}
	for _, source := range result.Trace.AnswerSources {
		sources[source.ID] = true
	}
	for _, id := range c.SourceIDs {
		if !sources[id] {
			issues = append(issues, fmt.Sprintf("required evidence missing: source %d", id))
		}
	}
	if len(c.AnySourceIDs) > 0 {
		found := false
		for _, id := range c.AnySourceIDs {
			found = found || sources[id]
		}
		if !found {
			issues = append(issues, "none of the equivalent reviewed sources was used")
		}
	}
	for _, rule := range c.Rules {
		if regexp.MustCompile(rule.Pattern).MatchString(result.Reply) == rule.Absent {
			issues = append(issues, rule.Reason)
		}
	}
	return issues
}

func agentEvalFingerprint(v any) string {
	raw, _ := json.Marshal(v)
	return fmt.Sprintf("%x", sha256.Sum256(raw))
}

func TestAgentEvaluationCatchesApprovedButWrongAnswers(t *testing.T) {
	c := agentEvalCase{ExpectedMode: "short", Outcome: "answer", Tools: []string{"check_answer"}, SourceIDs: []uint{27}, Rules: []agentEvalRule{
		{Reason: "wrong Laravel price", Pattern: `179[.,]?000`},
		{Reason: "invented recurring charge", Pattern: `(?i)per bulan`, Absent: true},
	}}
	good := ChatResult{Reply: "Kelas Laravel Rp179.000, sekali bayar untuk akses selamanya.", Trace: RetrievalTrace{
		ResponseValidated: true, ResponseMode: "short", ResponseMaxChars: 9999, ToolNames: "search_knowledge,check_answer", AnswerSources: []AnswerSource{{ID: 27}},
	}}
	if issues := gradeAgentEval(c, good); len(issues) != 0 {
		t.Fatal(issues)
	}
	for _, change := range []struct {
		name string
		edit func(*ChatResult)
	}{
		{"wrong_price_despite_guardrail", func(r *ChatResult) { r.Reply = "Kelas Laravel Rp199.000." }},
		{"wrong_condition", func(r *ChatResult) { r.Reply = "Rp179.000 per bulan." }},
		{"unnecessary_handoff", func(r *ChatResult) { r.Escalate = true }},
		{"missing_evidence", func(r *ChatResult) { r.Trace.AnswerSources = nil }},
		{"wrong_mode", func(r *ChatResult) { r.Trace.ResponseMode = "detailed" }},
		{"forged_character_cap", func(r *ChatResult) { r.Reply += strings.Repeat("x", 501) }},
		{"tool_name_substring", func(r *ChatResult) { r.Trace.ToolNames = "unchecked_answer" }},
	} {
		t.Run(change.name, func(t *testing.T) {
			r := good
			change.edit(&r)
			if len(gradeAgentEval(c, r)) == 0 {
				t.Fatal("independent evaluation accepted a known bad answer")
			}
		})
	}
}

func TestAgentEvaluationRejectsUnreviewedCustomerCases(t *testing.T) {
	s := agentEvalSuite{Version: 1, Name: "example", AgentID: 1, Cases: []agentEvalCase{{ID: "customer_one", Origin: "customer_replay", ReviewStatus: "draft", Reference: "human requested CS", Question: "CS manusia", Setting: "short", ExpectedMode: "short", Outcome: "handoff"}}}
	if validateAgentEvalSuite(s) == nil {
		t.Fatal("draft customer data must not become automatic ground truth")
	}
	s.Cases[0].ReviewStatus = "reviewed"
	if validateAgentEvalSuite(s) == nil {
		t.Fatal("customer data requires a privacy review")
	}
	s.Cases[0].PrivacyReviewed = true
	if err := validateAgentEvalSuite(s); err != nil {
		t.Fatal(err)
	}
}

func TestAgentEvaluationInvalidatesChangedReference(t *testing.T) {
	s := agentEvalSuite{AgentID: 1, References: []agentEvalReference{{ID: 27, Question: "Price?", Answer: "179000"}}}
	k := models.Knowledge{ID: 27, AgentID: 1, Question: "Price?", Answer: "179000", Active: true, ReviewStatus: "published"}
	if issues := agentEvalReferenceIssues(s, []models.Knowledge{k}, time.Now()); len(issues) != 0 {
		t.Fatal(issues)
	}
	k.Answer = "199000"
	if len(agentEvalReferenceIssues(s, []models.Knowledge{k}, time.Now())) == 0 {
		t.Fatal("stale expected price must invalidate the benchmark before API calls")
	}
	k.Answer = "179000"
	k.AgentID = 2
	if len(agentEvalReferenceIssues(s, []models.Knowledge{k}, time.Now())) == 0 {
		t.Fatal("matching facts from another assistant must not validate the reference")
	}
	k.AgentID = 1
	past := time.Now().Add(-time.Hour)
	k.EffectiveUntil = &past
	if len(agentEvalReferenceIssues(s, []models.Knowledge{k}, time.Now())) == 0 {
		t.Fatal("expired reference must invalidate the benchmark")
	}
}

func TestAgentEvaluationDefaultDataset(t *testing.T) {
	path := os.Getenv("CHATLOOP_EVAL_SUITE")
	if path == "" {
		path = "testdata/evaluations/ngertikode.v1.json"
	}
	if _, err := readAgentEvalSuite(path); err != nil {
		t.Fatal(err)
	}
}

func TestAgentEvaluationHandoffSignalContract(t *testing.T) {
	c := agentEvalCase{Outcome: "handoff", Tools: []string{"request_handoff"}}
	r := ChatResult{Escalate: true, HandoffReason: "customer_request", Trace: RetrievalTrace{ToolNames: "request_handoff"}}
	if issues := gradeAgentEval(c, r); len(issues) != 0 {
		t.Fatal(issues)
	}
	r.HandoffReason = ""
	if len(gradeAgentEval(c, r)) == 0 {
		t.Fatal("handoff without context must fail evaluation")
	}
	r.Escalate = false
	if len(gradeAgentEval(c, r)) == 0 {
		t.Fatal("an empty answer is not a handoff")
	}
}

func TestAgentEvaluationEquivalentSourcesStillRequireEvidence(t *testing.T) {
	c := agentEvalCase{Outcome: "answer", ExpectedMode: "short", AnySourceIDs: []uint{33, 43}}
	r := ChatResult{Reply: "Pesan massal terjadwal.", Trace: RetrievalTrace{ResponseValidated: true, ResponseMode: "short"}}
	if len(gradeAgentEval(c, r)) == 0 {
		t.Fatal("missing source passed")
	}
	r.Trace.AnswerSources = []AnswerSource{{ID: 34}}
	if len(gradeAgentEval(c, r)) == 0 {
		t.Fatal("unrelated source passed")
	}
	for _, id := range c.AnySourceIDs {
		r.Trace.AnswerSources = []AnswerSource{{ID: id}}
		if issues := gradeAgentEval(c, r); len(issues) > 0 {
			t.Fatal(issues)
		}
	}
}

func TestAgentEvaluationRejectsSwappedPrices(t *testing.T) {
	suite, err := readAgentEvalSuite("testdata/evaluations/ngertikode.v1.json")
	if err != nil {
		t.Fatal(err)
	}
	for _, c := range suite.Cases {
		if c.ID != "compare_prices" {
			continue
		}
		r := ChatResult{Reply: "- Laravel: Rp179.000\n- WA Blast: Rp199.000", Trace: RetrievalTrace{ResponseValidated: true, ResponseMode: "balanced", ToolNames: "search_knowledge,check_answer", AnswerSources: []AnswerSource{{ID: 70}, {ID: 28}}}}
		if issues := gradeAgentEval(c, r); len(issues) != 0 {
			t.Fatal(issues)
		}
		r.Reply = "- Laravel: Rp199.000\n- WA Blast: Rp179.000"
		if len(gradeAgentEval(c, r)) == 0 {
			t.Fatal("both prices are present but assigned to the wrong products")
		}
		return
	}
	t.Fatal("comparison regression is missing")
}
