#!/usr/bin/env python3
"""AAE Lab 05: explicit planning, execution state and bounded replanning."""
from dataclasses import dataclass, field

@dataclass
class Step:
    name: str
    status: str = "pending"
    evidence: str = ""

@dataclass
class RunState:
    goal: str
    plan: list[Step] = field(default_factory=list)
    completed_steps: int = 0
    max_steps: int = 6

state = RunState(
    goal="Investigate intermittent checkout latency",
    plan=[Step("check_service"), Step("inspect_recent_logs"), Step("summarize_evidence")],
)

FIXTURES = {
    "check_service": "healthy",
    "inspect_recent_logs": "upstream latency high",
    "inspect_upstream": "payments-api p95 latency high",
    "summarize_evidence": "root cause candidate: upstream dependency latency",
}

def next_pending(run: RunState):
    return next((step for step in run.plan if step.status == "pending"), None)

def maybe_replan(run: RunState, step: Step):
    if step.name == "inspect_recent_logs" and "upstream latency" in step.evidence:
        if not any(item.name == "inspect_upstream" for item in run.plan):
            index = next(i for i, item in enumerate(run.plan) if item.name == "summarize_evidence")
            run.plan.insert(index, Step("inspect_upstream"))
            print("REPLAN: inserted inspect_upstream because logs contain upstream-latency evidence")

print("AAE Lab 05 — explicit plan → execute → observe → replan\n")
while (step := next_pending(state)) is not None:
    if state.completed_steps >= state.max_steps:
        raise SystemExit("FAIL: step budget exhausted")
    print(f"EXECUTE: {step.name}")
    step.status = "running"
    step.evidence = FIXTURES[step.name]
    step.status = "complete"
    state.completed_steps += 1
    print(f"OBSERVE: {step.evidence}")
    maybe_replan(state, step)
    print("PLAN:", [(item.name, item.status) for item in state.plan], "\n")

assert state.completed_steps == 4
assert any(step.name == "inspect_upstream" and step.status == "complete" for step in state.plan)
assert state.completed_steps <= state.max_steps
print("✓ Plan completed within budget.")
print("✓ Replanning was triggered by explicit evidence, not hidden reasoning.")
