"""Integration management API endpoints."""

from __future__ import annotations

from fastapi import APIRouter, Request
from pydantic import BaseModel

router = APIRouter(prefix="/integrations", tags=["integrations"])


class ConnectRequest(BaseModel):
    credentials: dict


@router.get("")
async def list_integrations(request: Request) -> list[dict]:
    """List all integrations with connection status."""
    manager = request.app.state.integration_manager
    return await manager.list_integrations()


@router.post("/{name}/connect")
async def connect_integration(
    request: Request, name: str, body: ConnectRequest
) -> dict:
    """Connect an integration with credentials."""
    manager = request.app.state.integration_manager
    status = await manager.connect(name, body.credentials)
    return {"name": status.name, "connected": status.connected, "error": status.error}


@router.post("/{name}/disconnect")
async def disconnect_integration(request: Request, name: str) -> dict:
    """Disconnect an integration."""
    manager = request.app.state.integration_manager
    await manager.disconnect(name)
    return {"name": name, "connected": False}


@router.post("/sync")
async def sync_all(request: Request) -> dict:
    """Sync all connected integrations."""
    manager = request.app.state.integration_manager
    return await manager.sync_all()


@router.get("/registry")
async def get_registry(request: Request) -> dict:
    """Get the tool & integration registry — what the agent can do right now."""
    registry = request.app.state.registry
    return {
        "tools": registry.list_tools(),
        "integrations": registry.list_integrations(),
        "connected": registry.get_connected_integrations(),
    }
