#!/usr/bin/env python3
# Copyright (c) 2026 PULSE Contributors. Proprietary. All rights reserved.
# See LICENSE file for details.
"""
// PURPOSE: Central Brain Coordinator (The "Server").
// [Phase 2.1: Infrastructure - Kafka-Ready Architecture]
"""

import sys
import asyncio
import logging
from pathlib import Path

SCRIPT_DIR = Path(__file__).resolve().parent
ROOT_DIR = SCRIPT_DIR.parent.parent
from typing import Dict, List, Any

# Add Utilities to path

from pulse.admin.pulse_transaction import BrainTransaction

class BrainCoordinator:
    """
    // Orchestrates all incoming memory writes into a single-threaded queue.
    // This eliminates file contention and prepares the brain for Phase 2 scaling.
    """

    def __init__(self):
        self.queue = asyncio.Queue()
        self.tx = BrainTransaction(agent_id="brain_coordinator")
        self.running = True
        self.log = logging.getLogger("pulse.coordinator")

    async def enqueue_evidence(self, file_path: Path, evidence: List[Dict[str, Any]], agent_id: str):
        """// External agents call this to request a write."""
        request = {
            "path": file_path,
            "data": evidence,
            "agent_id": agent_id,
            "received_at": asyncio.get_event_loop().time()
        }
        await self.queue.put(request)
        print(f"  [QUEUE] Received {len(evidence)} items from {agent_id} for {file_path.name}")

    async def worker(self):
        """// The single-threaded processor that executes transactions one-by-one."""
        print("[PULSE] Brain Coordinator Worker Active.")
        while self.running:
            request = await self.queue.get()
            try:
                # Use our Phase 1.1 Atomic Signed Transaction layer
                success = self.tx.execute(request["path"], request["data"])
                if success:
                    print(f"  [COORDINATOR] Committed TX for {request['agent_id']} -> {request['path'].name}")
                else:
                    print(f"  [COORDINATOR_ERR] TX Failed for {request['agent_id']}")
            except Exception as e:
                print(f"  [COORDINATOR_CRASH] {str(e)}")
            finally:
                self.queue.task_done()

    async def stop(self):
        self.running = False

async def main():
    # Test simulation
    coord = BrainCoordinator()
    test_file = ROOT_DIR / "state" / "coord_test.json"
    
    # Start the worker in the background
    worker_task = asyncio.create_task(coord.worker())
    
    # Simulate multiple agents hitting the coordinator simultaneously
    print("[TEST] Simulating concurrent agent writes...")
    await asyncio.gather(
        coord.enqueue_evidence(test_file, [{"evidence": "Agent A discovery"}], "agent_a"),
        coord.enqueue_evidence(test_file, [{"evidence": "Agent B discovery"}], "agent_b"),
        coord.enqueue_evidence(test_file, [{"evidence": "Agent C discovery"}], "agent_c")
    )
    
    # Wait for processing
    await coord.queue.join()
    print("[TEST] All transactions processed.")
    worker_task.cancel()

if __name__ == "__main__":
    asyncio.run(main())
