"""Tests for self-state monitoring."""

import time

from social_alignment.types import AlignmentConfig, SelfStateFlag
from social_alignment.selfstate import SelfMonitor


class TestSelfMonitor:
    def test_starts_healthy(self):
        monitor = SelfMonitor(AlignmentConfig())
        state = monitor.check()
        assert state.is_healthy

    def test_detects_stale_context(self):
        config = AlignmentConfig(stale_context_seconds=10.0)
        monitor = SelfMonitor(config)
        monitor.update_context_age(60.0)  # 60s > 10s threshold
        state = monitor.check()
        assert SelfStateFlag.STALE_CONTEXT in state.flags

    def test_detects_tool_degradation(self):
        monitor = SelfMonitor(AlignmentConfig())
        monitor.report_tool_health("relay", True)
        monitor.report_tool_health("wallet", False)
        state = monitor.check()
        assert SelfStateFlag.TOOL_DEGRADED in state.flags

    def test_detects_rapid_decisions(self):
        config = AlignmentConfig(max_decisions_per_minute=3)
        monitor = SelfMonitor(config)
        # Record many decisions quickly
        for _ in range(10):
            monitor.record_decision(0.5)
        state = monitor.check()
        assert SelfStateFlag.RAPID_DECISIONS in state.flags

    def test_detects_low_confidence(self):
        config = AlignmentConfig(confidence_floor=0.4)
        monitor = SelfMonitor(config)
        for _ in range(5):
            monitor.record_decision(0.2)
        state = monitor.check()
        assert SelfStateFlag.HIGH_UNCERTAINTY in state.flags

    def test_detects_owner_absent(self):
        config = AlignmentConfig(owner_absent_hours=1.0)
        monitor = SelfMonitor(config)
        monitor.record_owner_interaction()
        # Backdate the interaction
        monitor._state.last_owner_interaction = time.time() - 7200  # 2 hours ago
        state = monitor.check()
        assert SelfStateFlag.OWNER_ABSENT in state.flags

    def test_force_and_clear_flag(self):
        monitor = SelfMonitor(AlignmentConfig())
        monitor.force_flag(SelfStateFlag.UNDER_INFLUENCE)
        assert SelfStateFlag.UNDER_INFLUENCE in monitor.state.flags
        assert not monitor.state.is_healthy

        monitor.clear_flag(SelfStateFlag.UNDER_INFLUENCE)
        assert monitor.state.is_healthy

    def test_snapshot(self):
        monitor = SelfMonitor(AlignmentConfig())
        monitor.record_owner_interaction()
        snap = monitor.snapshot()
        assert "flags" in snap
        assert "is_healthy" in snap
        assert snap["is_healthy"] is True
