import json
from pathlib import Path

from armorer.security.policy import PolicyGuard
from armorer.training_data import record_training_trace


def test_record_training_trace_writes_redacted_exports(tmp_path, monkeypatch):
    monkeypatch.setattr(Path, "home", lambda: tmp_path)
    guard = PolicyGuard.default()
    secret = "sk-abcdefghijklmnopqrstuvwxyz123456"

    result = record_training_trace(
        trace_id="trace-1",
        session_id="session-1",
        user_input=f"configure openclaw with {secret}",
        provider="ollama",
        model="armorer-qwen3.5-9b",
        system_prompt="You are helpful.",
        task_type="operational_or_factual",
        tool_names_exposed=["list_agents_structured"],
        attempts=[
                {
                    "attempt": 1,
                    "input": f"configure openclaw with {secret}",
                "tool_events": [{"type": "tool_call", "tool": "list_agents_structured"}],
                "final_output": '{"message": ""}',
                "failure_label": "empty_final",
            }
        ],
        final_response=f"Try `armorer config` with {secret}",
        outcome="success",
        failure_labels=["empty_final"],
        guard=guard,
    )

    raw_path = Path(result["raw_path"])
    assert raw_path.exists()
    raw = json.loads(raw_path.read_text())
    assert raw["user_input"] != f"configure openclaw with {secret}"
    assert "[REDACTED]" in raw["user_input"]
    assert raw["attempts"][0]["failure_label"] == "empty_final"

    sft_lines = (tmp_path / ".armorer" / "training_data" / "exports" / "sft.jsonl").read_text().splitlines()
    trajectory_lines = (tmp_path / ".armorer" / "training_data" / "exports" / "trajectories.jsonl").read_text().splitlines()
    assert len(sft_lines) == 1
    assert len(trajectory_lines) == 1
    sft = json.loads(sft_lines[0])
    assert sft["messages"][0]["role"] == "user"
    assert "[REDACTED]" in sft["messages"][0]["content"]
