"""Tests for executor-level dynamic replanning triggers."""

from __future__ import annotations

import pytest

from executor.action_executor import ActionExecutor


class TestDynamicReplanning:
    """Test SCAN_AREA trigger logic and replan callback emission."""

    def test_should_replan_when_scan_marked_interesting(self) -> None:
        executor = ActionExecutor()

        trigger, reasons = executor._should_replan_after_scan(
            {"analysis": "", "interesting": True}
        )

        assert trigger is True
        assert "scan_marked_interesting" in reasons

    def test_should_replan_when_analysis_has_keywords(self) -> None:
        executor = ActionExecutor()

        trigger, reasons = executor._should_replan_after_scan(
            {"analysis": "Chemical vapor observed near an unconscious worker."}
        )

        assert trigger is True
        joined = " ".join(reasons)
        assert "analysis_keywords:" in joined
        assert "chemical" in joined
        assert "vapor" in joined
        assert "unconscious" in joined

    @pytest.mark.asyncio
    async def test_execute_plan_emits_replan_callback_for_scan_area(self) -> None:
        async def suspicious_scan(_step, _context, _results):
            return {
                "analysis": "Possible gas leak with collapsed worker on the floor.",
                "interesting": True,
            }

        executor = ActionExecutor(handlers={"SCAN_AREA": suspicious_scan})

        plan = {
            "intent": "Inspect office",
            "workflow_topology": "DAG",
            "plan_id": "scan_plan_001",
            "steps": [
                {
                    "step_id": "scan1",
                    "type": "EXECUTION",
                    "agent_role": "robot",
                    "action": "SCAN_AREA",
                    "params": {"target": "office_tables"},
                }
            ],
        }

        signals = []

        def on_replan_requested(signal):
            signals.append(signal)

        report = await executor.execute_plan(plan, on_replan_requested=on_replan_requested)

        assert report.success is True
        assert len(signals) == 1
        assert signals[0]["type"] == "dynamic_replan_requested"
        assert signals[0]["step_id"] == "scan1"
        assert signals[0]["action"] == "SCAN_AREA"
        assert "scan_marked_interesting" in signals[0]["reasons"]
        assert signals[0]["scan_output"]["interesting"] is True
