package factcheck

import "testing"

func TestParseVerdictSupported(t *testing.T) {
	raw := "```json\n{\"verdict\":\"supported\",\"support_score\":88,\"claims\":[{\"claim\":\"a\",\"verdict\":\"supported\",\"evidence_index\":[0]}]}\n```"
	verdict, score, claims := parseVerdict(raw, 70)
	if verdict != "supported" {
		t.Fatalf("expected supported, got %q", verdict)
	}
	if score == nil || *score != 88 {
		t.Fatalf("expected score 88, got %v", score)
	}
	if len(claims) != 1 {
		t.Fatalf("expected 1 claim, got %d", len(claims))
	}
}

func TestParseVerdictDerivesFromClaims(t *testing.T) {
	// Model returns no top-level verdict; the engine must derive it from claims.
	raw := `{"claims":[{"claim":"x","verdict":"unsupported","evidence_index":[]}]}`
	verdict, _, _ := parseVerdict(raw, 70)
	if verdict != "unsupported" {
		t.Fatalf("expected unsupported, got %q", verdict)
	}
}

func TestParseVerdictEmptyClaimsUncertain(t *testing.T) {
	raw := `{"verdict":"","support_score":0,"claims":[]}`
	verdict, _, _ := parseVerdict(raw, 70)
	if verdict != "uncertain" {
		t.Fatalf("expected uncertain, got %q", verdict)
	}
}

func TestParseVerdictGarbageIsError(t *testing.T) {
	verdict, _, _ := parseVerdict("this is not json at all", 70)
	if verdict != "error" {
		t.Fatalf("expected error, got %q", verdict)
	}
}

func TestParseVerdictClampsScore(t *testing.T) {
	raw := `{"verdict":"supported","support_score":150,"claims":[{"claim":"a","verdict":"supported","evidence_index":[0]}]}`
	_, score, _ := parseVerdict(raw, 70)
	if score == nil || *score > 100 {
		t.Fatalf("score should be clamped to 100, got %v", score)
	}
}

func TestExtractJSONStripsFences(t *testing.T) {
	raw := "以下是结果：\n```json\n{\"a\":1}\n```\n完"
	if got := extractJSON(raw); got != `{"a":1}` {
		t.Fatalf("expected {\"a\":1}, got %q", got)
	}
}
