"""
Synqed Production Inbox - Complete Agent Email Infrastructure
"""
import os
from fastapi import FastAPI, APIRouter, HTTPException, status
from pydantic import BaseModel, HttpUrl
from typing import List, Dict, Any

from synqed.agent_email.inbox import router
from synqed.agent_email.inbox.startup import create_lifespan
from synqed.agent_email.registry.api import get_registry
from synqed.agent_email.registry.models import AgentRegistryEntry

# Configuration
REDIS_URL = os.getenv("REDIS_URL", "redis://localhost:6379")
PORT = int(os.getenv("PORT", "8000"))

# Create FastAPI app with lifespan management
app = FastAPI(
    title="Synqed Agent Email System",
    version="2.0.0",
    description="Production-grade A2A inbox with cryptographic identity, guaranteed delivery, and distributed tracing",
    lifespan=create_lifespan(redis_url=REDIS_URL),
)

# Include inbox router
app.include_router(router)

# Registration models
class AgentRegistrationRequest(BaseModel):
    agent_id: str
    email_like: str
    inbox_url: HttpUrl
    public_key: str
    capabilities: List[str] = ["a2a/1.0"]
    metadata: Dict[str, Any] = {}

class AgentRegistrationResponse(BaseModel):
    status: str
    agent_id: str
    email_like: str
    message: str

# Registration endpoints
@app.post("/v1/a2a/register", response_model=AgentRegistrationResponse, tags=["registration"])
async def register_agent(request: AgentRegistrationRequest):
    """Register a new agent - anyone can register!"""
    registry = get_registry()
    
    try:
        registry.get_by_uri(request.agent_id)
        raise HTTPException(status_code=409, detail="Agent already registered")
    except KeyError:
        pass
    
    entry = AgentRegistryEntry(
        agent_id=request.agent_id,
        email_like=request.email_like,
        inbox_url=request.inbox_url,
        public_key=request.public_key,
        capabilities=request.capabilities,
        metadata=request.metadata,
    )
    registry.register(entry)
    
    return AgentRegistrationResponse(
        status="registered",
        agent_id=request.agent_id,
        email_like=request.email_like,
        message=f"Agent {request.email_like} registered successfully!"
    )

@app.get("/v1/a2a/agents", tags=["registration"])
async def list_agents():
    """List all registered agents."""
    registry = get_registry()
    agents = registry.list_all()
    return {
        "count": len(agents),
        "agents": [{"agent_id": a.agent_id, "email_like": a.email_like, "inbox_url": str(a.inbox_url)} for a in agents]
    }

@app.get("/v1/a2a/agents/{email_like}", tags=["registration"])
async def lookup_agent(email_like: str):
    """Lookup agent by email address."""
    registry = get_registry()
    try:
        agent = registry.get_by_email(email_like)
        return {"agent_id": agent.agent_id, "email_like": agent.email_like, "inbox_url": str(agent.inbox_url)}
    except KeyError:
        raise HTTPException(status_code=404, detail="Agent not found")

@app.get("/")
async def root():
    """Service information."""
    return {
        "service": "Synqed Agent Email System",
        "version": "2.0.0",
        "status": "operational",
        "endpoints": {
            "health": "/health",
            "docs": "/docs",
            "inbox": "/v1/a2a/inbox",
            "register": "POST /v1/a2a/register",
        "list_agents": "GET /v1/a2a/agents",
        "lookup_agent": "GET /v1/a2a/agents/{email}",
        },
        "features": {
            "cryptographic_identity": "Ed25519 signatures",
            "guaranteed_delivery": "Redis Streams queue",
            "rate_limiting": "100/min per sender, 500/min per IP",
            "distributed_tracing": "trace_id propagation",
            "retry_policy": "5 retries with exponential backoff",
            "dead_letter_queue": "Failed messages after max retries",
        }
    }

@app.get("/health")
async def health():
    """Health check for monitoring and load balancers."""
    return {
        "status": "healthy",
        "version": "2.0.0",
        "redis": REDIS_URL,
    }

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=PORT, log_level="info")
