"""
GENESIS COORDINATOR
===================
The Autonomous Brain of the Genesis System.
Cycles: Observes Task.md -> Plans Action -> Executes Skill -> Reflects to Memory.

Usage:
    python genesis_coordinator.py --loop
"""

import time
import sys
import os
import json
from datetime import datetime
from typing import List, Dict, Optional

# Genesis Imports
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
from blackboard import Blackboard, EntryType, TaskStatus
from genesis_memory_cortex import MemoryCortex
from genesis_skills import GenesisSkills
from tool_router import ToolRouter

class GenesisCoordinator:
    """
    Orchestrator Brain of Genesis.
    Coordinates the swarm via the Intelligent Tool Router.
    """
    
    def __init__(self):
        self.bb = Blackboard()
        self.cortex = MemoryCortex()
        self.router = ToolRouter()
        self.namespace = "genesis:coordinator"
        
        print(f"[OK] Genesis Orchestrator Coordinator Initialized [TURBO MODE]")
        print(f"[OK] Homebase: grounded | Burst: GCP ready")

    def observe(self) -> List[Dict]:
        """Query open tasks from the Blackboard."""
        return self.bb.query(entry_type=EntryType.TASK, status=TaskStatus.OPEN)

    def execute_loop(self):
        print(f"[{datetime.now().isoformat()}] Coordinator Active.")
        
        while True:
            # 1. Observe
            open_tasks = self.observe()
            if not open_tasks:
                time.sleep(30)
                continue
                
            print(f"\n>>> FOUND {len(open_tasks)} OPEN TASKS")
            
            for task in open_tasks:
                print(f"    Routing Task: {task.id} - {task.content.get('track', 'General')}")
                
                # 2. Claim (Atomic locking)
                # Note: In a production swarm, workers claim, but Coordinator manages routing.
                
                # 3. Plan & Route (USING INTELLIGENT ROUTER)
                task_desc = f"{task.content.get('track', '')}: {task.content.get('description', '')}"
                
                # 4. Act (DISPATCH)
                try:
                    success = self.router.dispatch(task.id, task_desc)
                    
                    if success:
                        # Mark task as completed on Blackboard after successful skill run
                        # This assumes the skill execution is synchronous for the coordinator
                        # self.bb.update_status(task.id, TaskStatus.COMPLETED)
                        print(f"    [SUCCESS] Task {task.id[:8]} executed.")
                    
                    # Log activity
                    self.bb.write(
                        entry_type=EntryType.DECISION,
                        content={"action": "routed_task", "task_id": task.id, "success": success},
                        author=self.namespace,
                        tags=["coordination", "routing"]
                    )
                    
                except Exception as e:
                    print(f"    [ERR] Routing failure for {task.id}: {e}")
            
            time.sleep(10)

if __name__ == "__main__":
    coordinator = GenesisCoordinator()
    coordinator.execute_loop()
