"""Tests for decision memory and wisdom generation."""

from social_alignment.types import (
    ActionDomain,
    Decision,
    LensResult,
    Lens,
    Projection,
    Severity,
)
from social_alignment.memory import DecisionMemory


def _make_decision(domain=ActionDomain.EXECUTE, proceeded=True, overrode=False) -> Decision:
    lr = LensResult(Lens.BUILDER, Severity.CLEAR, "ok", "", "")
    proj = Projection(
        action_domain=domain,
        action_description=f"test {domain.value}",
        lens_results=(lr,),
        overall_severity=Severity.CLEAR,
        should_proceed=True,
        should_escalate=False,
        rationale="test",
    )
    return Decision(projection=proj, chose_to_proceed=proceeded, owner_overrode=overrode)


class TestDecisionMemory:
    def test_record_and_count(self):
        mem = DecisionMemory()
        mem.record(_make_decision())
        assert mem.count == 1

    def test_max_decisions_enforced(self):
        mem = DecisionMemory(max_decisions=5)
        for _ in range(10):
            mem.record(_make_decision())
        assert mem.count == 5

    def test_find_similar(self):
        mem = DecisionMemory()
        mem.record(_make_decision(ActionDomain.PAY))
        mem.record(_make_decision(ActionDomain.EXECUTE))
        mem.record(_make_decision(ActionDomain.PAY))

        similar = mem.find_similar(ActionDomain.PAY)
        assert len(similar) == 2

    def test_owner_override_rate(self):
        mem = DecisionMemory()
        for i in range(10):
            mem.record(_make_decision(overrode=(i < 3)))

        rate = mem.owner_override_rate(10)
        assert 0.29 < rate < 0.31

    def test_outcome_match_rate_no_data(self):
        mem = DecisionMemory()
        mem.record(_make_decision())
        rate = mem.outcome_match_rate()
        assert rate == 0.5  # No outcomes recorded = moderate default

    def test_outcome_match_rate_with_data(self):
        mem = DecisionMemory()
        for i in range(10):
            dec = _make_decision()
            dec = dec.record_outcome("ok", matched=(i < 8))
            mem.record(dec)
        rate = mem.outcome_match_rate(10)
        assert 0.79 < rate < 0.81

    def test_wisdom_report(self):
        mem = DecisionMemory()
        for _ in range(20):
            mem.record(_make_decision())
        report = mem.review()
        assert report.total_decisions == 20
        assert report.decisions_reviewed == 20
        assert isinstance(report.insights, list)

    def test_roundtrip(self):
        mem = DecisionMemory()
        mem.record(_make_decision())
        mem.record(_make_decision(ActionDomain.PAY))
        d = mem.to_dict()
        restored = DecisionMemory.from_dict(d)
        assert restored.count == 2

    def test_recent(self):
        mem = DecisionMemory()
        for i in range(15):
            mem.record(_make_decision())
        assert len(mem.recent) == 10
