import json
import tempfile
import unittest
from pathlib import Path

from policyfaultbench.cost import BudgetExceeded, CostGuard
from policyfaultbench.events import EventWriter, RunEvent


class CostAndEventTests(unittest.TestCase):
    def test_hard_budget_stops_overspend(self):
        guard = CostGuard({"x": 0.01}, 0.01, {"x": (10.0, 10.0)})
        with self.assertRaises(BudgetExceeded):
            guard.preflight("x", 2000, 0)

    def test_event_log_redacts_and_is_jsonl(self):
        with tempfile.TemporaryDirectory() as directory:
            path = Path(directory) / "events.jsonl"
            EventWriter(path).append(
                RunEvent.create("run-1", "model_request", {"api_key": "do-not-store"})
            )
            row = json.loads(path.read_text(encoding="utf-8"))
            self.assertEqual(row["payload"]["api_key"], "[REDACTED]")
            self.assertEqual(len(row["payload_hash"]), 64)


if __name__ == "__main__":
    unittest.main()
