"""CAP HTTP Agent Bridge — Lightweight cross-agent HTTP server.

A minimal FastAPI app exposing only cross-agent endpoints.
Runs as a background task alongside the MCP stdio server in VS Code,
enabling other SOAGILA products to discover and query this instance.

For the Desktop sidecar (http_bridge.py), these endpoints are added
directly to the existing FastAPI app instead.
"""

import json
import logging
import socket

import uvicorn
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse

logger = logging.getLogger("soagila.cap.bridge")


def _find_free_port() -> int:
    """Find a free port on localhost."""
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        s.bind(("127.0.0.1", 0))
        return s.getsockname()[1]


def create_agent_app() -> FastAPI:
    """Create the cross-agent HTTP bridge FastAPI app."""
    app = FastAPI(title="SOAGILA Agent Bridge", version="1.0.0")

    app.add_middleware(
        CORSMiddleware,
        allow_origins=["*"],
        allow_methods=["*"],
        allow_headers=["*"],
    )

    @app.get("/health")
    async def health():
        from soagila.core.cap.discovery import get_current_product_type
        return JSONResponse({
            "success": True,
            "data": {
                "status": "ok",
                "product": get_current_product_type() or "vscode",
                "protocol": "cap",
            },
        })

    @app.get("/agent/info")
    async def agent_info():
        """Return this agent's identity and capabilities."""
        from soagila.core.cap.discovery import get_self_info
        info = await get_self_info()
        if info is None:
            return JSONResponse(
                {"success": False, "error": "Agent not registered"},
                status_code=503,
            )
        return JSONResponse({"success": True, "data": info})

    @app.get("/agent/peers")
    async def agent_peers():
        """List known peer agents from the registry."""
        from soagila.core.cap.discovery import get_peer_agents
        peers = await get_peer_agents(same_project_only=False)
        return JSONResponse({"success": True, "data": peers})

    @app.post("/agent/recall")
    async def agent_recall(request: Request):
        """Handle cross-agent recall: query this agent's memories."""
        body = await request.json()
        from soagila.core.cap.protocol import handle_cross_recall
        try:
            result = await handle_cross_recall(body)
            return JSONResponse({"success": True, "data": result})
        except ValueError as e:
            return JSONResponse(
                {"success": False, "error": str(e)},
                status_code=403,
            )
        except Exception as e:
            logger.error(f"Cross-agent recall error: {e}", exc_info=True)
            return JSONResponse(
                {"success": False, "error": str(e)},
                status_code=500,
            )

    @app.post("/agent/notify")
    async def agent_notify(request: Request):
        """Receive notification from a peer agent."""
        body = await request.json()
        from soagila.core.cap.protocol import handle_notification
        try:
            result = await handle_notification(body)
            return JSONResponse({"success": True, "data": result})
        except ValueError as e:
            return JSONResponse(
                {"success": False, "error": str(e)},
                status_code=403,
            )

    return app


async def start_bridge() -> int:
    """Start the HTTP agent bridge in a background task. Returns the port."""
    port = _find_free_port()
    app = create_agent_app()

    config = uvicorn.Config(
        app,
        host="127.0.0.1",
        port=port,
        log_level="warning",
        access_log=False,
    )
    server = uvicorn.Server(config)

    import asyncio
    asyncio.create_task(server.serve())

    logger.info(f"Agent bridge started on port {port}")
    return port
