"""Tests for knowledge record models."""

from datetime import datetime, timezone

from fliiq.runtime.knowledge.models import (
    Anchor,
    KnowledgeRecord,
    Provenance,
    RecordType,
    SourceType,
)


def test_record_defaults():
    """A minimal record gets sane defaults."""
    rec = KnowledgeRecord(
        type=RecordType.DECISION,
        source=SourceType.HUMAN_IN_LOOP,
        context="SMS provider selection",
        decision="Use Twilio for SMS",
        rationale="Best pricing and reliability for our volume",
    )
    assert rec.id.startswith("kr_")
    assert rec.confidence == 0.8
    assert rec.domain == ""
    assert rec.tags == []
    assert rec.constraints == []
    assert rec.expired is False
    assert rec.anchor is None
    assert rec.provenance is None
    assert isinstance(rec.created_at, datetime)
    assert isinstance(rec.updated_at, datetime)


def test_record_all_fields():
    """All fields serialize and deserialize correctly."""
    rec = KnowledgeRecord(
        type=RecordType.DOMAIN_RULE,
        source=SourceType.AGENT_INFERENCE,
        context="claims_adjudication.process_claim()",
        decision="Short-circuit before payer verification for preventive care",
        rationale="ACA Section 2713 mandates coverage without cost-sharing",
        constraints=["aca_section_2713", "preventive_care_mandate"],
        confidence=0.95,
        domain="healthcare_billing",
        tags=["regulatory", "compliance"],
        provenance=Provenance(source_type="cli", agent_id="agent-123"),
        anchor=Anchor(file="src/claims.py", line_start=142, line_end=168, content_hash="abc123"),
        alternatives_considered=["Run full payer pipeline"],
        scope="global",
        expiry_conditions="When ACA regulations change",
        related_records=["kr_other123"],
    )

    # Round-trip through JSON
    json_str = rec.model_dump_json()
    loaded = KnowledgeRecord.model_validate_json(json_str)

    assert loaded.type == RecordType.DOMAIN_RULE
    assert loaded.confidence == 0.95
    assert loaded.anchor.file == "src/claims.py"
    assert loaded.anchor.line_start == 142
    assert loaded.provenance.agent_id == "agent-123"
    assert loaded.constraints == ["aca_section_2713", "preventive_care_mandate"]
    assert loaded.alternatives_considered == ["Run full payer pipeline"]
    assert loaded.related_records == ["kr_other123"]


def test_record_type_enum():
    """All record types are valid."""
    for t in ("decision", "constraint", "heuristic", "domain_rule"):
        assert RecordType(t).value == t


def test_source_type_enum():
    """All source types are valid."""
    for s in ("human_in_loop", "agent_decision", "agent_inference"):
        assert SourceType(s).value == s


def test_confidence_bounds():
    """Confidence must be between 0 and 1."""
    import pytest

    with pytest.raises(Exception):
        KnowledgeRecord(
            type=RecordType.DECISION,
            source=SourceType.HUMAN_IN_LOOP,
            context="test",
            decision="test",
            rationale="test",
            confidence=1.5,
        )

    with pytest.raises(Exception):
        KnowledgeRecord(
            type=RecordType.DECISION,
            source=SourceType.HUMAN_IN_LOOP,
            context="test",
            decision="test",
            rationale="test",
            confidence=-0.1,
        )


def test_anchor_optional_fields():
    """Anchor can have only a file, no lines or hash."""
    anchor = Anchor(file="src/main.py")
    assert anchor.line_start is None
    assert anchor.line_end is None
    assert anchor.content_hash is None


def test_provenance_minimal():
    """Provenance can be minimal."""
    prov = Provenance(source_type="telegram")
    assert prov.agent_id is None
    assert prov.task_id is None


def test_unique_ids():
    """Each record gets a unique ID."""
    rec1 = KnowledgeRecord(
        type=RecordType.HEURISTIC,
        source=SourceType.AGENT_DECISION,
        context="test",
        decision="test",
        rationale="test",
    )
    rec2 = KnowledgeRecord(
        type=RecordType.HEURISTIC,
        source=SourceType.AGENT_DECISION,
        context="test",
        decision="test",
        rationale="test",
    )
    assert rec1.id != rec2.id


def test_utcnow_timezone():
    """Timestamps should be timezone-aware UTC."""
    rec = KnowledgeRecord(
        type=RecordType.DECISION,
        source=SourceType.HUMAN_IN_LOOP,
        context="test",
        decision="test",
        rationale="test",
    )
    assert rec.created_at.tzinfo == timezone.utc
