"""Tool → Provider assignment endpoints."""

from typing import Any

import structlog
from fastapi import APIRouter, HTTPException
from pydantic import BaseModel, Field

from proxym.tools import ToolRegistry

logger = structlog.get_logger()
router = APIRouter(tags=["tools"])


class ToolProviderRequest(BaseModel):
    tool: str = Field(..., description="Tool name")
    provider: str = Field(..., description="Provider name (openrouter, anthropic, openai, ollama, ...)")


@router.post("/provider")
async def set_tool_provider(req: ToolProviderRequest) -> dict[str, Any]:
    """Assign an LLM provider to a specific tool."""
    from proxym.config import get_settings
    settings = get_settings()

    tool = ToolRegistry.get().get_tool(req.tool)
    if not tool:
        raise HTTPException(404, f"Tool '{req.tool}' not found")

    configured = settings.available_providers()
    if req.provider not in configured and req.provider != "openrouter":
        raise HTTPException(400,
            f"Provider '{req.provider}' not configured. "
            f"Available: {', '.join(configured.keys())}")

    settings.tool_providers[req.tool] = req.provider
    logger.info("tool_provider_set", tool=req.tool, provider=req.provider)
    return {
        "ok": True,
        "tool": req.tool,
        "provider": req.provider,
        "all_mappings": settings.tool_providers,
    }


@router.get("/providers")
async def get_tool_providers() -> dict[str, Any]:
    """Get current tool → provider mappings."""
    from proxym.config import get_settings
    settings = get_settings()
    configured = settings.available_providers()
    return {
        "tool_providers": settings.tool_providers,
        "available_providers": list(configured.keys()),
    }
