#!/usr/bin/env python3
# Copyright (c) 2026 PULSE Contributors. Proprietary. All rights reserved.
# See LICENSE file for details.
"""
// PURPOSE: Minimalist, Async-First SDK for PULSE Agents.
// [Phase 2.2: Infrastructure - Agent SDK]
"""

import asyncio
import sys
from dataclasses import dataclass, asdict
from datetime import datetime, timezone
from pathlib import Path

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

# Add project roots to path

from pulse.core.pulse_crypto import PulseCrypto

# Attempt to load coordinator for internal routing
try:
    from pulse.api.pulse_coordinator import BrainCoordinator
except ImportError:
    pass

@dataclass
class EvidencePayload:
    """// Strict Type Definition for Evidence [TYPE_TITAN]"""
    evidence: str
    domain: str
    type: str = "observation"
    source: str = "agent_sdk"
    timestamp: Optional[float] = None
    visibility: str = "public"
    pattern: str = "uncategorized"

class PulseClient:
    """
    // The "Phone" agents use to call the Brain.
    // Optimized for sub-10ms latency [LATENCY_LAYER].
    """

    def __init__(self, agent_id: str, coordinator: Optional[Any] = None):
        self.agent_id = agent_id
        self.coordinator = coordinator
        self.crypto = PulseCrypto()

    async def push(self, domain: str, text: str, 
                   e_type: str = "observation", 
                   pattern: str = "uncategorized") -> bool:
        """
        // Main entrypoint for agents.
        """
        payload = EvidencePayload(
            evidence=text,
            domain=domain,
            type=e_type,
            source=self.agent_id,
            timestamp=datetime.now(timezone.utc).timestamp(),
            pattern=pattern
        )
        
        return await self._send_to_coordinator(payload)

    async def _send_to_coordinator(self, payload: EvidencePayload) -> bool:
        """// Internal routing logic [KAFKA_MAGE]"""
        try:
            if self.coordinator:
                # Internal Queue Routing (High Speed)
                file_name = f"{payload.domain}_captured.json" if payload.domain != "session" else "current_session.json"
                target_path = ROOT_DIR / "Hippocampus" / "Episodic" / "Raw_Evidence" / file_name
                
                await self.coordinator.enqueue_evidence(
                    target_path, 
                    [asdict(payload)], 
                    self.agent_id
                )
                return True
            else:
                return False
        except Exception as e:
            print(f"  [SDK_ERROR] {str(e)}")
            return False

if __name__ == "__main__":
    # Test SDK with Mock Coordinator
    async def test_sdk():
        print("=== PULSE Agent SDK Test ===")
        # Dynamic import to handle test pathing
        DAEMON_DIR = ROOT_DIR / "pulse" / "api"
        from pulse.api.pulse_coordinator import BrainCoordinator
        
        mock_coord = BrainCoordinator()
        worker = asyncio.create_task(mock_coord.worker())
        
        client = PulseClient(agent_id="test_agent_sdk", coordinator=mock_coord)
        
        print("[SDK] Pushing test evidence...")
        success = await client.push("general", "SDK integration successful", e_type="win")
        
        if success:
            print("[SDK] Push accepted by coordinator.")
        
        # Wait for processing
        await asyncio.sleep(0.5)
        await mock_coord.queue.join()
        worker.cancel()

    asyncio.run(test_sdk())