#!/usr/bin/env python3
"""
register_telnyx_tools.py
Registers AIVA tools with Telnyx Voice Assistant API
"""

import os
import sys
import json
import logging
import requests
from typing import List, Dict, Any, Optional

from core.secrets_loader import get_telnyx_api_key

logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)

# Configuration
TELNYX_API_KEY = get_telnyx_api_key()
ASSISTANT_ID = os.getenv("TELNYX_ASSISTANT_ID", "assistant-696799a5-e994-4ac1-8f26-7b0923aee682")
WEBHOOK_BASE_URL = os.getenv("WEBHOOK_BASE_URL", "https://api.genesis.example.com")

# Tool Definitions
TOOLS: List[Dict[str, Any]] = [
    {
        "name": "relay_directive_to_claude",
        "description": "Relays Kinan's spoken directives to Claude Code for processing. Use this when Kinan gives a command, asks a question, or requests status updates that require Claude Code intervention.",
        "webhook_url": f"{WEBHOOK_BASE_URL}/bridge/telnyx/relay_directive",
        "parameters": {
            "type": "object",
            "properties": {
                "directive_text": {
                    "type": "string",
                    "description": "The exact spoken directive from Kinan to be relayed to Claude Code"
                },
                "priority": {
                    "type": "integer",
                    "minimum": 1,
                    "maximum": 10,
                    "default": 5,
                    "description": "Priority level of the directive (1-10, where 10 is highest)"
                },
                "directive_type": {
                    "type": "string",
                    "enum": ["task", "query", "status_request", "urgent"],
                    "description": "Classification of the directive type"
                }
            },
            "required": ["directive_text"]
        }
    },
    {
        "name": "check_claude_status",
        "description": "Checks what Claude Code is currently doing and retrieves recent history if requested. Use this when Kinan asks about current tasks or progress.",
        "webhook_url": f"{WEBHOOK_BASE_URL}/bridge/telnyx/check_status",
        "parameters": {
            "type": "object",
            "properties": {
                "include_history": {
                    "type": "boolean",
                    "default": False,
                    "description": "Whether to include recent task history"
                },
                "history_limit": {
                    "type": "integer",
                    "default": 5,
                    "minimum": 1,
                    "maximum": 50,
                    "description": "Number of historical items to return if include_history is true"
                }
            }
        }
    }
]

class TelnyxToolRegistrar:
    def __init__(self, api_key: str, assistant_id: str):
        self.api_key = api_key
        self.assistant_id = assistant_id
        self.base_url = "https://api.telnyx.com/v2"
        self.headers = {
            "Authorization": f"Bearer {api_key}",
            "Content-Type": "application/json",
            "Accept": "application/json"
        }
    
    def update_assistant_tools(self, tools: List[Dict[str, Any]]) -> Optional[Dict]:
        """PATCH assistant with new tools configuration"""
        url = f"{self.base_url}/ai/assistants/{self.assistant_id}"
        
        payload = {
            "tools": tools,
            "tool_webhook_url": f"{WEBHOOK_BASE_URL}/bridge/telnyx"  # Base path for tool webhooks
        }
        
        try:
            logger.info(f"Updating assistant {self.assistant_id} with {len(tools)} tools")
            logger.debug(f"Payload: {json.dumps(payload, indent=2)}")
            
            response = requests.patch(
                url,
                headers=self.headers,
                json=payload,
                timeout=30
            )
            
            response.raise_for_status()
            result = response.json()
            
            logger.info("Successfully registered tools with Telnyx")
            return result
            
        except requests.exceptions.HTTPError as e:
            logger.error(f"HTTP Error {e.response.status_code}: {e.response.text}")
            raise
        except requests.exceptions.RequestException as e:
            logger.error(f"Request failed: {e}")
            raise
    
    def verify_assistant(self) -> bool:
        """Verify assistant exists and is accessible"""
        url = f"{self.base_url}/ai/assistants/{self.assistant_id}"
        
        try:
            response = requests.get(url, headers=self.headers, timeout=10)
            response.raise_for_status()
            data = response.json()
            logger.info(f"Assistant verified: {data.get('data', {}).get('name', 'Unknown')}")
            return True
        except Exception as e:
            logger.error(f"Failed to verify assistant: {e}")
            return False

def save_tool_definitions(tools: List[Dict], filename: str = "telnyx_tools.json"):
    """Save tool definitions to JSON file for reference"""
    try:
        with open(filename, 'w', encoding='utf-8') as f:
            json.dump(tools, f, indent=2, ensure_ascii=False)
        logger.info(f"Tool definitions saved to {filename}")
    except IOError as e:
        logger.error(f"Failed to save tool definitions: {e}")

def main():
    logger.info("Starting Telnyx Tool Registration")
    
    if not all([TELNYX_API_KEY, ASSISTANT_ID, WEBHOOK_BASE_URL]):
        logger.error("Missing required environment variables")
        sys.exit(1)
    
    registrar = TelnyxToolRegistrar(TELNYX_API_KEY, ASSISTANT_ID)
    
    try:
        if not registrar.verify_assistant():
            sys.exit(1)
        
        result = registrar.update_assistant_tools(TOOLS)
        
        if result:
            save_tool_definitions(TOOLS)
            logger.info("Registration complete")
            print(json.dumps(result, indent=2))
            
    except Exception as e:
        logger.error(f"Registration failed: {e}")
        sys.exit(1)

if __name__ == "__main__":
    main()