from src.models import Ticket
from src.dag_engine import TrackDAG, ExecutionEngine

def test_execution_engine_basic_flow():
 t1 = Ticket(id="T1", description="desc", status="todo", assigned_to="worker1")
 t2 = Ticket(id="T2", description="desc", status="todo", assigned_to="worker1", depends_on=["T1"])
 dag = TrackDAG([t1, t2])
 engine = ExecutionEngine(dag)
 
 # 1. First tick
 ready = engine.tick()
 assert len(ready) == 1
 assert ready[0].id == "T1"
 assert ready[0].status == "todo" # Not auto-queued yet
 
 # 2. Mark T1 in_progress
 # update_task_status updates the underlying Ticket object.
 engine.update_task_status("T1", "in_progress")
 # tick() returns 'todo' tasks that are ready. T1 is in_progress, so it's not 'todo'.
 ready = engine.tick()
 assert len(ready) == 0
 
 # 3. Mark T1 complete
 engine.update_task_status("T1", "completed")
 # Now T2 should be ready
 ready = engine.tick()
 assert len(ready) == 1
 assert ready[0].id == "T2"

def test_execution_engine_update_nonexistent_task():
 dag = TrackDAG([])
 engine = ExecutionEngine(dag)
 # Should not crash
 engine.update_task_status("NONEXISTENT", "completed")

def test_execution_engine_status_persistence():
 t1 = Ticket(id="T1", description="desc", status="todo", assigned_to="worker1")
 dag = TrackDAG([t1])
 engine = ExecutionEngine(dag)
 engine.update_task_status("T1", "in_progress")
 assert t1.status == "in_progress"

def test_execution_engine_auto_queue():
 t1 = Ticket(id="T1", description="desc", status="todo", assigned_to="worker1")
 t2 = Ticket(id="T2", description="desc", status="todo", assigned_to="worker1", depends_on=["T1"])
 dag = TrackDAG([t1, t2])
 engine = ExecutionEngine(dag, auto_queue=True)
 
 # Tick should return T1
 ready = engine.tick()
 assert len(ready) == 1
 assert ready[0].id == "T1"
 
 # Mark T1 complete
 engine.update_task_status("T1", "completed")
 ready = engine.tick()
 assert len(ready) == 1
 assert ready[0].id == "T2"

def test_execution_engine_step_mode():
 t1 = Ticket(id="T1", description="desc", status="todo", assigned_to="worker1", step_mode=True)
 dag = TrackDAG([t1])
 engine = ExecutionEngine(dag, auto_queue=True)
 
 # Even with auto_queue, step_mode task requires manual approval
 ready = engine.tick()
 assert len(ready) == 1
 assert ready[0].id == "T1"
 assert ready[0].status == "todo"
 
 # Manual approval
 engine.approve_task("T1")
 assert t1.status == "in_progress"

def test_execution_engine_approve_task():
 t1 = Ticket(id="T1", description="desc", status="todo", assigned_to="worker1")
 dag = TrackDAG([t1])
 engine = ExecutionEngine(dag)
 engine.approve_task("T1")
 assert t1.status == "in_progress"
