#!/usr/bin/env python3
"""
AIVA Tool Bridge - Genesis Command Centre Liaison
==================================================
Handles webhooks from AIVA (Telnyx AI Assistant) to relay directives
to the Claude terminal and report system status back to her.

Endpoints:
    POST /webhooks/aiva/directive - Relay voice directive to Claude
    GET  /webhooks/aiva/status    - Get system status for AIVA to read
    POST /webhooks/aiva/log       - Log conversation summary
"""

import os
import json
import logging
from datetime import datetime
from pathlib import Path
from fastapi import FastAPI, Request, HTTPException
from pydantic import BaseModel

# Add project root to sys.path
GENESIS_ROOT = Path("/mnt/e/genesis-system")
import sys
sys.path.insert(0, str(GENESIS_ROOT))

try:
    from core.blackboard import Blackboard, EntryType, TaskStatus
except ImportError:
    # Manual path if needed
    sys.path.insert(0, str(GENESIS_ROOT / "core"))
    from blackboard import Blackboard, EntryType, TaskStatus

app = FastAPI(title="AIVA Tool Bridge")
blackboard = Blackboard(use_redis=True)

class DirectiveRequest(BaseModel):
    directive: str
    priority: str = "normal"

class LogRequest(BaseModel):
    summary: str
    outcome: str
    caller_mood: str

@app.post("/webhooks/aiva/directive")
async def relay_directive(req: DirectiveRequest):
    """Relay a voice command to the Claude terminal via the Blackboard."""
    print(f"[AIVA BRIDGE] Received Directive: {req.directive} (Priority: {req.priority})")
    
    entry = blackboard.add_task(
        task_name="Voice Directive",
        description=req.directive,
        priority=req.priority,
        tags=["voice", "aiva", "kinan"]
    )
    
    # Also append to a dedicated voice command file for easy terminal monitoring
    with open(GENESIS_ROOT / "data" / "voice_directives.log", "a") as f:
        f.write(f"[{datetime.now().isoformat()}] {req.priority.upper()}: {req.directive}
")
        
    return {"status": "relayed", "entry_id": entry.id}

@app.get("/webhooks/aiva/status")
async def get_status():
    """Report the current system status for AIVA to read back."""
    # Read the work queue for the most up-to-date human-readable status
    queue_path = GENESIS_ROOT / ".gemini" / "knowledge" / "WORK_QUEUE_TODAY.md"
    if queue_path.exists():
        content = queue_path.read_text()
        # Find first few incomplete tasks
        import re
        tasks = re.findall(r"- \[ \] (.*)", content)
        if tasks:
            status_text = f"Currently working on: {tasks[0]}. "
            if len(tasks) > 1:
                status_text += f"Next in queue: {tasks[1]}."
        else:
            status_text = "All primary tasks in the current queue are marked as complete."
    else:
        status_text = "The Genesis system is online and monitoring the blackboard."

    # Add active swarm info
    try:
        with open(GENESIS_ROOT / "data" / "daily_budget.json") as f:
            budget = json.load(f)
            active_swarms = len(budget.get("agent_runs", []))
            status_text += f" There are {active_swarms} active agent swarms running right now."
    except:
        pass

    return {"status": "online", "report": status_text}

@app.post("/webhooks/aiva/log")
async def log_conversation(req: LogRequest):
    """Log conversation summary for system learning."""
    print(f"[AIVA BRIDGE] Logging Conversation: {req.summary}")
    
    blackboard.add_entry(
        entry_type=EntryType.FINDING,
        content={
            "summary": req.summary,
            "outcome": req.outcome,
            "caller_mood": req.caller_mood
        },
        source="aiva_voice_call",
        tags=["learning", "interaction"]
    )
    
    return {"status": "logged"}

if __name__ == "__main__":
    import uvicorn
    # Port 8765 is often used for the bridge in Genesis
    uvicorn.run(app, host="0.0.0.0", port=8765)
