"""
TDD: Navigation Trap Recovery & UNKNOWN Screen Handling

1. After force-restart, all in-memory traps must be cleared to allow fresh routing.
2. Traps on UNKNOWN screens must NEVER persist — UNKNOWN is a catch-all,
   permanent traps here block ALL unidentified screens.
3. Trap system must have time-decay — old traps expire after a threshold.
"""

import pytest


class TestNavigationTrapRecovery:
    """Trap system must not create permanent dead-ends."""

    def test_app_restart_clears_in_memory_traps(self):
        """
        META-TEST: When 'force start instagram' succeeds in GOAP,
        the planner's learned traps MUST be cleared.
        """
        import inspect
        from GramAddict.core.goap import GoalExecutor

        source = inspect.getsource(GoalExecutor.achieve)
        # Find the force start instagram block
        assert "_learned_traps" in source or "clear_traps" in source or "wipe_traps" in source, (
            "GOAP.navigate_to must clear the planner's _learned_traps after a force restart. "
            "Currently only action_failures and explored_nav_actions are cleared, "
            "leaving traps active — which causes immediate re-trapping on restart."
        )

    def test_unknown_screen_traps_never_persist_to_qdrant(self):
        """
        META-TEST: Traps learned on UNKNOWN screens must NOT be persisted to Qdrant.
        UNKNOWN is a catch-all — persisting traps here blocks ALL unidentified screens forever.
        """
        import inspect
        from GramAddict.core.navigation.knowledge import NavigationKnowledge

        source = inspect.getsource(NavigationKnowledge.learn_trap)
        source_lower = source.lower()

        # Must have a guard against persisting UNKNOWN traps
        assert "unknown" in source_lower, (
            "learn_trap must guard against persisting traps on UNKNOWN screens. "
            "UNKNOWN is a catch-all — permanent traps here block ALL unidentified screens."
        )

    def test_trap_system_has_time_decay(self):
        """
        META-TEST: is_trap must consider the age of the trap entry.
        Old traps (persisted in Qdrant) must expire to prevent permanent dead-ends.
        """
        import inspect
        from GramAddict.core.navigation.knowledge import NavigationKnowledge

        source = inspect.getsource(NavigationKnowledge.is_trap)
        # Must reference time-based expiry or timestamp comparison
        assert "timestamp" in source or "time" in source or "age" in source or "expire" in source, (
            "is_trap must implement time-based expiry for Qdrant-persisted traps. "
            "Permanent traps cause permanent dead-ends."
        )
