"""Unit tests for PublishAuditor."""
from __future__ import annotations

import json
from pathlib import Path

from ana.audit import PublishAuditor


def test_audit_log_writes_jsonl(tmp_path: Path) -> None:
    log = tmp_path / "audit.jsonl"
    a = PublishAuditor(log_path=log)
    a.track("cc.fleet.alice.query.status", 128, "query")
    a.track("cc.fleet.alice.reply.status", 200, "reply")

    lines = log.read_text(encoding="utf-8").splitlines()
    assert len(lines) == 2
    e0 = json.loads(lines[0])
    assert e0["subject"] == "cc.fleet.alice.query.status"
    assert e0["bytes"] == 128
    assert e0["type"] == "query"


def test_rate_threshold_trips(tmp_path: Path) -> None:
    a = PublishAuditor(log_path=None, default_rate_threshold=3)
    for _ in range(5):
        a.track("cc.fleet.spammer", 10, "query")
    assert any(t[0] == "cc.fleet.spammer" for t in a.trips)


def test_per_subject_threshold_override(tmp_path: Path) -> None:
    a = PublishAuditor(log_path=None, default_rate_threshold=100)
    a.set_threshold("cc.fleet.tight", 2)
    for _ in range(5):
        a.track("cc.fleet.tight", 10, "query")
    assert any(t[0] == "cc.fleet.tight" for t in a.trips)
    # default-threshold subject should not trip
    for _ in range(10):
        a.track("cc.fleet.loose", 10, "query")
    assert not any(t[0] == "cc.fleet.loose" for t in a.trips)


def test_audit_log_missing_dir_is_created(tmp_path: Path) -> None:
    log = tmp_path / "nested" / "dir" / "audit.jsonl"
    a = PublishAuditor(log_path=log)
    a.track("cc.fleet.alice.query.status", 1, "query")
    assert log.exists()
    assert json.loads(log.read_text())["bytes"] == 1


def test_reset_trips() -> None:
    a = PublishAuditor(default_rate_threshold=1)
    a.track("s", 1, "query")
    a.track("s", 1, "query")
    assert a.trips
    a.reset_trips()
    assert not a.trips
