"""Tests for xmldev.audit — Patch records and AuditWriter."""
from __future__ import annotations

import json
import tempfile
from pathlib import Path

import pytest

from xmldev.audit import AuditWriter, Patch


def test_patch_defaults():
    p = Patch(type="rename", path="/root[1]/name[1]", original="<fullname>", replacement="<name>",
               rule_id="fuzzy_rename_v1", confidence=0.95)
    assert p.source == "deterministic"
    assert p.auto_applied is False  # default; must be set by repairer
    assert p.id  # uuid generated


def test_patch_auto_applied_high_confidence():
    p = Patch(type="rename", path="/x", original="a", replacement="b",
               rule_id="test", confidence=0.95, auto_applied=True)
    assert p.auto_applied is True


def test_patch_to_dict_has_all_fields():
    p = Patch(type="insert", path="/root[1]", original="", replacement="<status>pending</status>",
               rule_id="default_insertion_v1", confidence=0.95, auto_applied=True)
    d = p.to_dict()
    for field in ("id", "type", "path", "original", "replacement", "rule_id",
                  "confidence", "auto_applied", "timestamp", "source", "notes"):
        assert field in d, f"Missing field: {field}"


def test_audit_writer_build_summary():
    patches = [
        Patch(type="rename", path="/a", original="x", replacement="y", rule_id="r1", confidence=0.95, auto_applied=True),
        Patch(type="coerce", path="/b", original="1", replacement="2", rule_id="r2", confidence=0.6, auto_applied=False),
        Patch(type="insert", path="/c", original="", replacement="z", rule_id="r3", confidence=0.95, auto_applied=True, source="llm"),
    ]
    summary = AuditWriter.build_summary(patches)
    assert summary["total_patches"] == 3
    assert summary["auto_applied"] == 2
    assert summary["pending_review"] == 1
    assert summary["by_type"]["rename"] == 1
    assert summary["by_type"]["coerce"] == 1
    assert summary["by_source"]["deterministic"] == 2
    assert summary["by_source"]["llm"] == 1


def test_audit_writer_write_to_file():
    p1 = Patch(type="rename", path="/root[1]/name[1]", original="<fullname>", replacement="<name>",
               rule_id="alias_rename_v1", confidence=1.0, auto_applied=True)
    with tempfile.NamedTemporaryFile(suffix=".json", delete=False) as f:
        path = f.name
    AuditWriter.write([p1], path)
    audit = json.loads(Path(path).read_text())
    assert "summary" in audit
    assert "patches" in audit
    assert audit["summary"]["total_patches"] == 1
    assert audit["patches"][0]["type"] == "rename"


def test_audit_writer_to_dict():
    p1 = Patch(type="delete", path="/x", original="<bad>", replacement="", rule_id="r", confidence=1.0)
    result = AuditWriter.to_dict([p1])
    assert isinstance(result["patches"], list)
    assert result["patches"][0]["type"] == "delete"
