"""
Tests for Bot Flow Curiosity Logic
==================================
Ensures that the spontaneous CHECK_CURIOSITY feature correctly shifts context
and relies on structural safety (navigating to HomeFeed) rather than hallucinating
clicks on invalid screens like Profiles.
"""

from GramAddict.core.bot_flow import _run_zero_latency_feed_loop
from GramAddict.core.session_state import SessionState
from tests.e2e.conftest import load_fixture_xml
from tests.e2e.device_emulator import create_emulator_facade

HOME_FEED_XML = load_fixture_xml("home_feed_real.xml")
PROFILE_XML = load_fixture_xml("other_profile_real.xml")


def _build_curiosity_state_machine():
    states = {
        "home_feed": HOME_FEED_XML,
        "other_profile": PROFILE_XML,
    }

    transitions = {
        "home_feed": {
            "clicks": [
                ({"id": "com.instagram.android:id/row_feed_photo_profile_name"}, "other_profile"),
            ],
            "press": [
                ("back", "home_feed"),
            ],
        },
        "other_profile": {
            "clicks": [
                ({"desc": "Home"}, "home_feed"),
                ({"id": "com.instagram.android:id/feed_tab"}, "home_feed"),
            ],
            "press": [
                ("back", "home_feed"),
            ],
        },
    }

    return states, transitions


def test_curiosity_navigates_to_homefeed_before_checking(
    e2e_configs, e2e_cognitive_stack_factory, setup_e2e_plugin_registry, monkeypatch
):
    """
    Simulates the feed loop starting on other_profile.
    When CHECK_CURIOSITY triggers, it must FIRST navigate to HomeFeed before
    trying to 'tap heart icon notifications'.
    """
    # We do NOT mock production code. No bf.sleep or _humanized_scroll mocking.
    import random
    import time

    random.seed(31)  # First random.random() is 0.057 < 0.06, triggers CHECK_CURIOSITY

    # 1. Setup emulator starting on other_profile
    states, transitions = _build_curiosity_state_machine()
    device, emulator = create_emulator_facade("other_profile", states, transitions, monkeypatch)

    # 2. Setup REAL Config & SessionState
    configs = e2e_configs

    session_state = SessionState(configs)

    # 4. Setup Cognitive Stack
    cognitive_stack = e2e_cognitive_stack_factory(device)
    nav_graph = cognitive_stack["nav_graph"]
    zero_engine = cognitive_stack["zero_engine"]
    dopamine = cognitive_stack["dopamine"]
    growth = cognitive_stack["growth_brain"]

    # Force CHECK_CURIOSITY
    monkeypatch.setattr(growth, "evaluate_governance", lambda *args, **kwargs: "CHECK_CURIOSITY")

    # We want it to exit cleanly after executing a few loops, without hanging forever.
    dopamine.session_limit_seconds = 0.1
    dopamine.session_start = time.time()

    # 5. Run the loop (starting from other_profile)
    # 5. Run the loop (starting from other_profile)
    _run_zero_latency_feed_loop(
        device=device,
        zero_engine=zero_engine,
        nav_graph=nav_graph,
        configs=configs,
        session_state=session_state,
        job_target="homefeed",
        cognitive_stack=cognitive_stack,
    )

    # 6. Assertions: Must navigate to HomeFeed FIRST
    assert emulator.current_state == "home_feed", (
        "Curiosity failed to navigate to HomeFeed before executing! " f"Bot is stuck on {emulator.current_state}"
    )
