package services

import (
	"encoding/json"
	"os"
	"path/filepath"
	"strings"
	"testing"
)

func readPrivacyLog(t *testing.T, s *SimulationLogStore, id string) string {
	t.Helper()
	raw, err := os.ReadFile(filepath.Join(s.dir, "agent-1", id+".jsonl"))
	if err != nil {
		t.Fatal(err)
	}
	return string(raw)
}

func TestDiagnosticPrivacyDefaultStoresMetadataOnly(t *testing.T) {
	t.Setenv("AI_SIMULATION_LOG_CONTENT", "false")
	s := NewSimulationLogStore(t.TempDir())
	id := NewSimulationID()
	r, err := s.Start(1, id, NewSimulationID(), map[string]any{"question": "private-question", "history_used": []any{"private-history"}, "settings": map[string]any{"response_length": "short", "system_prompt": "private-prompt"}})
	if err != nil {
		t.Fatal(err)
	}
	r.Record("tool_completed", "search_knowledge", "completed", map[string]any{"input": map[string]any{"query": "private-query"}, "output": map[string]any{"answer": "private-document"}, "issue": "missing_evidence", "duration_ms": 12, "input_tokens": 34, "unknown": map[string]any{"future": "private-future"}})
	r.Finish("completed", map[string]any{"reply": "private-reply", "error": "private-error", "response_chars": 13, "tool_calls": 2, "knowledge_ids": "1,2"})
	raw := readPrivacyLog(t, s, id)
	if strings.Contains(raw, "private-") {
		t.Fatal("default log persisted customer or retrieved content")
	}
	for _, want := range []string{"missing_evidence", `"duration_ms":12`, `"input_tokens":34`, `"response_chars":13`, `"tool_calls":2`, `"knowledge_ids":"1,2"`} {
		if !strings.Contains(raw, want) {
			t.Errorf("metadata lost: %s", want)
		}
	}
}

func TestDiagnosticPrivacyOptInRedactsCredentialsAndKeepsRunChoice(t *testing.T) {
	t.Setenv("AI_SIMULATION_LOG_CONTENT", "true")
	s := NewSimulationLogStore(t.TempDir())
	id := NewSimulationID()
	r, err := s.Start(1, id, NewSimulationID(), map[string]any{"question": "debug question", "system_prompt": "secret-system"})
	if err != nil {
		t.Fatal(err)
	}
	t.Setenv("AI_SIMULATION_LOG_CONTENT", "false")
	r.Record("tool_completed", "lookup_products", "completed", map[string]any{"output": map[string]any{"accessToken": "secret-access", "answer": "Bearer secret-bearer-value", "nested": "{\"password\":\"secret-password\"}", "url": "https://example.test/?token=secret-url"}, "reasoning_content": "secret-reasoning"})
	r.Finish("completed", map[string]any{"reply": "debug reply"})
	raw := readPrivacyLog(t, s, id)
	if strings.Contains(raw, "secret-") {
		t.Fatal("credential or internal content leaked in debug log")
	}
	if !strings.Contains(raw, "debug question") || !strings.Contains(raw, "debug reply") {
		t.Fatal("explicit run-level debug choice was lost")
	}
}

func TestDiagnosticPrivacyReadHidesPreviouslyStoredContentWhenDisabled(t *testing.T) {
	t.Setenv("AI_SIMULATION_LOG_CONTENT", "true")
	s := NewSimulationLogStore(t.TempDir())
	id := NewSimulationID()
	r, err := s.Start(1, id, NewSimulationID(), map[string]any{"question": "stored-private-question"})
	if err != nil {
		t.Fatal(err)
	}
	r.Finish("completed", map[string]any{"reply": "stored-private-reply", "response_chars": 20})
	before := readPrivacyLog(t, s, id)
	t.Setenv("AI_SIMULATION_LOG_CONTENT", "false")
	log, err := s.Read(1, id)
	if err != nil {
		t.Fatal(err)
	}
	raw, _ := json.Marshal(log)
	if strings.Contains(string(raw), "stored-private") {
		t.Fatal("disabled export exposed an older detailed log")
	}
	if readPrivacyLog(t, s, id) != before {
		t.Fatal("privacy read mutated existing file")
	}
}

func TestDiagnosticPrivacyFeedbackExplicitAndRedacted(t *testing.T) {
	t.Setenv("AI_SIMULATION_LOG_CONTENT", "false")
	s := NewSimulationLogStore(t.TempDir())
	id := NewSimulationID()
	r, err := s.Start(1, id, NewSimulationID(), nil)
	if err != nil {
		t.Fatal(err)
	}
	r.Finish("completed", nil)
	if err := s.Feedback(1, id, "needs_work", "Harga perlu diperiksa. password=secret-note", 7); err != nil {
		t.Fatal(err)
	}
	log, err := s.Read(1, id)
	if err != nil {
		t.Fatal(err)
	}
	raw, _ := json.Marshal(log)
	if strings.Contains(string(raw), "secret-note") || !strings.Contains(string(raw), "Harga perlu diperiksa") {
		t.Fatal("explicit feedback was lost or credential remained")
	}
}

func TestDiagnosticPrivacyUnknownFieldsAndErrorTextAreNotMetadata(t *testing.T) {
	t.Setenv("AI_SIMULATION_LOG_CONTENT", "false")
	s := NewSimulationLogStore(t.TempDir())
	id := NewSimulationID()
	r, err := s.Start(1, id, NewSimulationID(), nil)
	if err != nil {
		t.Fatal(err)
	}
	r.Record("tool_issue", "search_knowledge", "error", map[string]any{"issue": "knowledge_unavailable", "notice": "private notice", "error": "private error", "output": map[string]any{"query": "private query"}, "model_calls": 3, "model_call_limit": 16})
	r.Finish("error", map[string]any{"error": "private final error", "answer_check_issue": "knowledge_unavailable"})
	raw := readPrivacyLog(t, s, id)
	if strings.Contains(raw, "private") || !strings.Contains(raw, "knowledge_unavailable") || !strings.Contains(raw, `"model_calls":3`) {
		t.Fatal("privacy boundary lost safe diagnostics or persisted content")
	}
}
