#!/usr/bin/env python3
"""
Simple CLI tool to chat with Aiva (Genesis Prime Coordinator)
Uses Letta API on localhost:8283
"""

import requests
import json
import sys
from datetime import datetime

# Configuration
LETTA_API_BASE = "http://localhost:8283/v1"
AIVA_AGENT_ID = "agent-35039b24-fbb9-4139-b036-4a04e9c3d6ac"

def send_message(message: str):
    """Send a message to Aiva and get her response"""
    url = f"{LETTA_API_BASE}/agents/{AIVA_AGENT_ID}/messages"
    
    payload = {
        "messages": [
            {
                "role": "user",
                "text": message
            }
        ]
    }
    
    try:
        response = requests.post(url, json=payload, timeout=120)
        response.raise_for_status()
        
        data = response.json()
        
        # Extract Aiva's response from the messages
        if "messages" in data:
            for msg in data["messages"]:
                if msg.get("role") == "assistant":
                    # Return the text content
                    if "text" in msg and msg["text"]:
                        return msg["text"]
                    # Or parse from content array
                    elif "content" in msg and isinstance(msg["content"], list):
                        for content_item in msg["content"]:
                            if content_item.get("type") == "text":
                                return content_item.get("text", "")
        
        return json.dumps(data, indent=2)
    
    except requests.exceptions.RequestException as e:
        return f"Error communicating with Aiva: {e}"

def get_agent_info():
    """Get Aiva's current state"""
    url = f"{LETTA_API_BASE}/agents/{AIVA_AGENT_ID}"
    
    try:
        response = requests.get(url)
        response.raise_for_status()
        data = response.json()
        
        return {
            "name": data.get("name"),
            "description": data.get("description"),
            "message_count": len(data.get("message_ids", [])),
            "last_updated": data.get("updated_at")
        }
    except Exception as e:
        return {"error": str(e)}

def interactive_mode():
    """Start interactive chat session with Aiva"""
    print("=" * 70)
    print("  AIVA - GENESIS PRIME COORDINATOR")
    print("  Chat Interface via Letta API")
    print("=" * 70)
    
    # Get agent info
    info = get_agent_info()
    if "error" not in info:
        print(f"\nAgent: {info['name']}")
        print(f"Description: {info['description']}")
        print(f"Messages in history: {info['message_count']}")
        print(f"Last updated: {info['last_updated']}")
    
    print("\nType 'quit' or 'exit' to end the conversation")
    print("Type 'info' to see Aiva's current state")
    print("=" * 70)
    print()
    
    while True:
        try:
            # Get user input
            user_input = input("You: ").strip()
            
            if not user_input:
                continue
            
            if user_input.lower() in ['quit', 'exit', 'q']:
                print("\nEnding conversation with Aiva. Goodbye!")
                break
            
            if user_input.lower() == 'info':
                print("\n[Fetching Aiva's current state...]")
                info = get_agent_info()
                print(json.dumps(info, indent=2))
                print()
                continue
            
            # Send message to Aiva
            print("\n[Sending to Aiva...]")
            response = send_message(user_input)
            
            # Display response
            print(f"\nAiva: {response}")
            print()
        
        except KeyboardInterrupt:
            print("\n\nInterrupted. Ending conversation.")
            break
        except Exception as e:
            print(f"\nError: {e}")
            print()

def single_message_mode(message: str):
    """Send a single message and exit"""
    print(f"Sending to Aiva: {message}\n")
    response = send_message(message)
    print(f"Aiva's response:\n{response}")

def main():
    """Main entry point"""
    if len(sys.argv) > 1:
        # Single message mode
        message = " ".join(sys.argv[1:])
        single_message_mode(message)
    else:
        # Interactive mode
        interactive_mode()

if __name__ == "__main__":
    main()
