"""
E2E: Hard-Kill Timeout Validation
==================================
Tests that the `--max-runtime-minutes` parameter works as an absolute
hard-kill, deeply breaking the dopamine engine and orchestrator loops.
"""

from datetime import datetime, timedelta

from GramAddict.core.dopamine_engine import DopamineEngine


def test_dopamine_hard_kill_timeout_triggered():
    """
    Verifies that the DopamineEngine correctly interrupts the session
    if the global maximum runtime is exceeded, regardless of baseline boredom.
    """
    engine = DopamineEngine()

    # Baseline: Session should NOT be over
    assert engine.is_app_session_over() is False

    # Inject global limits
    engine.global_start_time = datetime.now()
    engine.global_max_runtime_minutes = 2

    # Should still not be over (we just started)
    assert engine.is_app_session_over() is False

    # Time warp: Simulate 3 minutes passing
    engine.global_start_time = datetime.now() - timedelta(minutes=3)

    # The engine should now trigger a hard kill
    assert engine.is_app_session_over() is True, "DopamineEngine failed to trigger Hard-Kill on timeout!"


def test_goap_hard_kill_timeout_triggered(make_real_device_with_xml):
    """
    Verifies that the GoalExecutor aborts its planning loop and returns False
    if the global maximum runtime is exceeded.
    """
    from GramAddict.core.goap import GoalExecutor

    from tests.e2e.conftest import load_fixture_xml

    xml = load_fixture_xml("home_feed_with_ad.xml")
    device = make_real_device_with_xml(xml)

    # Reset singleton/class variables
    GoalExecutor._instance = None
    GoalExecutor.global_start_time = datetime.now()
    GoalExecutor.global_max_runtime_minutes = 2

    goap = GoalExecutor.get_instance(device, bot_username="testuser")

    # Time warp: Simulate 3 minutes passing
    GoalExecutor.global_start_time = datetime.now() - timedelta(minutes=3)

    try:
        # The achieve loop should immediately exit and return False
        result = goap.achieve("open profile")
        assert result is False, "GoalExecutor failed to abort achieve loop on Hard-Kill timeout!"
    finally:
        GoalExecutor.global_max_runtime_minutes = None
        GoalExecutor.global_start_time = None



