"""
demo server with pre-registered cosmos and gemini runtimes.

this server is specifically for running the cosmos_gemini_demo.py via http.
it includes mock agent runtimes that are registered on startup.

run with: python demos/demo_server.py
"""

import uuid
from typing import Any, Dict

from synqed.agent_email.main import app
from synqed.agent_email.inbox.api import LocalAgentRuntime, register_agent_runtime


class CosmosRuntime(LocalAgentRuntime):
    """
    mock runtime for cosmos agent.
    
    cosmos analyzes startup ideas and sends them to other agents for review.
    """
    
    async def handle_a2a_envelope(
        self,
        sender: str,
        recipient: str,
        envelope: Dict[str, Any],
    ) -> Dict[str, Any] | None:
        """handle incoming envelope (cosmos mostly sends, doesn't receive much)."""
        print(f"\n[cosmos] received message from {sender}")
        print(f"[cosmos] content: {envelope.get('content', '')}")
        
        # cosmos could respond, but for this demo it's the initiator
        return None


class GeminiRuntime(LocalAgentRuntime):
    """
    mock runtime for gemini agent.
    
    gemini provides structured analysis of startup ideas.
    """
    
    async def handle_a2a_envelope(
        self,
        sender: str,
        recipient: str,
        envelope: Dict[str, Any],
    ) -> Dict[str, Any] | None:
        """handle incoming envelope and generate analysis."""
        print(f"\n[gemini] received message from {sender}")
        print(f"[gemini] thread_id: {envelope.get('thread_id', 'unknown')}")
        print(f"[gemini] content: {envelope.get('content', '')}")
        
        # extract the startup idea from content
        content = envelope.get("content", "")
        
        # generate structured analysis (mock)
        analysis = f"""
structured analysis of the proposal:

1. problem statement: {content[:100]}...
2. market potential: high demand in academic and biotech sectors
3. technical feasibility: requires robust nlp and reasoning capabilities
4. competitive advantage: integration with a2a protocol for agent collaboration
5. recommendation: proceed with mvp development

this analysis was generated by gemini@google via the agent email layer.
        """.strip()
        
        # create response envelope
        response = {
            "thread_id": envelope.get("thread_id", str(uuid.uuid4())),
            "role": "assistant",
            "content": analysis,
            "tool_calls": [],
        }
        
        print(f"[gemini] sending response with analysis")
        
        return response


# register demo runtimes on module load (before server starts)
print("registering demo agent runtimes...")
register_agent_runtime("agent://futurehouse/cosmos", CosmosRuntime())
register_agent_runtime("agent://google/gemini", GeminiRuntime())
print("✓ registered cosmos and gemini runtimes")


if __name__ == "__main__":
    import uvicorn
    
    print("\n" + "="*70)
    print("AGENT EMAIL LAYER - DEMO SERVER")
    print("="*70)
    print("\nStarting server with pre-registered demo runtimes:")
    print("  - cosmos@futurehouse (agent://futurehouse/cosmos)")
    print("  - gemini@google (agent://google/gemini)")
    print("\nServer will be available at: http://localhost:8000")
    print("API docs: http://localhost:8000/docs")
    print("\nTo run the demo, in another terminal:")
    print("  cd /Users/dorsa/Desktop/PROJECTS/synq_2/synqed-python")
    print("  python demos/cosmos_gemini_demo.py")
    print("="*70 + "\n")
    
    # pass app object directly instead of import string
    # (avoids module resolution issues)
    uvicorn.run(
        app,
        host="0.0.0.0",
        port=8000,
    )

