import time
from enum import Enum, auto
from core.blackboard import Blackboard


class Phase(Enum):
    RECEIVE = 1
    WARN = 2
    TENTATIVE_PLAN = 3
    START_MOVEMENT = 4
    RECON = 5
    COMPLETE_PLAN = 6
    ISSUE_ORDER = 7
    REFINE_SUPERVISE = 8
    LOOP = 9


class TLPGateLoop:
    """
    The 9-step Troops Leading Procedures (TLP) Gate Loop.
    Coupled with S' for replan triggers.
    """

    def __init__(self, blackboard: Blackboard):
        self.bb = blackboard
        self.current_phase = Phase.RECEIVE

    def step(self):
        """Advances the state machine."""
        print(f"[*] TLP: Phase {self.current_phase.name}")

        if self.current_phase == Phase.RECEIVE:
            self._receive_mission()
        elif self.current_phase == Phase.WARN:
            self._issue_warning()
        elif self.current_phase == Phase.TENTATIVE_PLAN:
            self._make_tentative_plan()
        elif self.current_phase == Phase.REFINE_SUPERVISE:
            self._refine_and_supervise()

        # Simple linear progression for mockup
        if self.current_phase.value < 8:
            self.current_phase = Phase(self.current_phase.value + 1)
        else:
            self.current_phase = Phase.LOOP

    def _receive_mission(self):
        obj = self.bb.read("objective")
        if obj:
            print(f"    Mission: {obj}")

    def _issue_warning(self):
        # Notify user of intent/risk
        print("    Warning: Execution commencing. Risks: [Latency, Cost]")

    def _make_tentative_plan(self):
        # This is where the Hybrid model usually fires
        plan = ["Search", "Read", "Edit", "Verify"]
        self.bb.set_plan(plan, "TLP_ENGINE")

    def _refine_and_supervise(self):
        # Monitoring step
        print("    Supervising execution metrics...")
        metrics = self.bb.read("metrics")
        if metrics["errors"] > 0:
            print("    [!] REPLAN TRIGGERED due to errors.")
            self.current_phase = Phase.TENTATIVE_PLAN
