package usecase

import (
	"testing"
)

func TestParseLLMResponse_ValidJSON(t *testing.T) {
	input := `[
		{
			"question": "Ist eine Datenschutz-Folgenabschaetzung durchgefuehrt?",
			"pass_criteria": ["DSFA dokumentiert"],
			"fail_criteria": ["Keine DSFA"],
			"severity": "HIGH"
		},
		{
			"question": "Sind Betroffenenrechte implementiert?",
			"pass_criteria": ["Prozess vorhanden"],
			"fail_criteria": ["Kein Prozess"],
			"severity": "MEDIUM"
		}
	]`

	result := parseLLMResponse(input)
	if len(result) != 2 {
		t.Fatalf("Expected 2 questions, got %d", len(result))
	}
	if result[0].Question != "Ist eine Datenschutz-Folgenabschaetzung durchgefuehrt?" {
		t.Errorf("Unexpected question: %s", result[0].Question)
	}
	if result[0].Severity != "HIGH" {
		t.Errorf("Expected HIGH severity, got %s", result[0].Severity)
	}
}

func TestParseLLMResponse_WithPreamble(t *testing.T) {
	input := `Hier sind die Prueffragen:

[{"question":"Test?","pass_criteria":["OK"],"fail_criteria":["NOK"],"severity":"LOW"}]

Ich hoffe das hilft.`

	result := parseLLMResponse(input)
	if len(result) != 1 {
		t.Fatalf("Expected 1 question from wrapped response, got %d", len(result))
	}
}

func TestParseLLMResponse_InvalidJSON(t *testing.T) {
	result := parseLLMResponse("This is not JSON at all")
	if result != nil {
		t.Errorf("Expected nil for invalid JSON, got %v", result)
	}
}

func TestParseLLMResponse_EmptyQuestion(t *testing.T) {
	input := `[
		{"question":"","pass_criteria":["OK"],"fail_criteria":["NOK"],"severity":"HIGH"},
		{"question":"Valid?","pass_criteria":["Yes"],"fail_criteria":["No"],"severity":"LOW"}
	]`

	result := parseLLMResponse(input)
	if len(result) != 1 {
		t.Fatalf("Expected 1 valid question (empty filtered), got %d", len(result))
	}
	if result[0].Question != "Valid?" {
		t.Errorf("Unexpected question: %s", result[0].Question)
	}
}

func TestBuildPrompt(t *testing.T) {
	mc := MCInfo{
		MasterControlID: "MC-123",
		CanonicalName:   "access_control_mfa",
		TotalControls:   12,
		RegSource:       "NIS2",
	}

	prompt := buildPrompt(mc, []string{"nis2", "dsgvo"})

	if prompt == "" {
		t.Error("Expected non-empty prompt")
	}
	if !contains(prompt, "access control mfa") {
		t.Error("Prompt should contain readable MC name")
	}
	if !contains(prompt, "12 Atomic Controls") {
		t.Error("Prompt should contain control count")
	}
}

func contains(s, sub string) bool {
	return len(s) >= len(sub) && (s == sub || len(s) > 0 && containsSubstring(s, sub))
}

func containsSubstring(s, sub string) bool {
	for i := 0; i+len(sub) <= len(s); i++ {
		if s[i:i+len(sub)] == sub {
			return true
		}
	}
	return false
}
