"""Context, session, and MCP endpoints — extracted from main.py."""

from __future__ import annotations

import structlog
from fastapi import APIRouter, Request

from proxym.context import detect_project

from proxym.api._state import (
    get_mcp_router,
    get_session_store,
    set_context_payload,
)

logger = structlog.get_logger()

router = APIRouter()


@router.post("/v1/context/delta")
async def receive_delta(request: Request):
    """Receive context delta from the file watcher client."""
    body = await request.json()
    set_context_payload(body.get("payload", ""))
    return {
        "ok": True,
        "version": body.get("version"),
        "token_estimate": body.get("token_estimate"),
    }


@router.post("/v1/context/detect")
async def detect_context(request: Request):
    """Detect project context from request body (messages + headers)."""
    body = await request.json()
    messages = body.get("messages", [])
    headers = {k.lower(): v for k, v in request.headers.items()}
    ctx = detect_project(messages, headers=headers)
    return {
        "project_id": ctx.project_id,
        "project_name": ctx.project_name,
        "project_root": ctx.project_root,
        "stack": ctx.stack,
        "git_remote": ctx.git_remote,
    }


@router.get("/v1/sessions")
async def list_sessions():
    """List active agent sessions."""
    store = get_session_store()
    return {
        "sessions": [
            {
                "session_id": s.session_id,
                "project_id": s.project_id,
                "age_seconds": round(s.age_seconds, 1),
                "idle_seconds": round(s.idle_seconds, 1),
                "history_length": len(s.compressed_history),
                "active_files": s.active_files,
            }
            for s in store.list_sessions()
        ],
    }


@router.get("/v1/mcp/servers")
async def list_mcp_servers():
    """List registered MCP servers."""
    mcp_router = get_mcp_router()
    servers = mcp_router.registry.list_servers(enabled_only=False)
    return {
        "servers": [
            {
                "name": s.name,
                "url": s.url,
                "transport": s.transport.value,
                "tools": s.tools,
                "enabled": s.enabled,
                "priority": s.priority,
                "description": s.description,
            }
            for s in servers
        ],
    }
