"""Internal API router for platform-to-agent management.

Protected by a shared secret (ROOHAI_INTERNAL_TOKEN env var).
These endpoints are called by the platform API, not by end users.
"""

from __future__ import annotations

import logging
import os

from fastapi import APIRouter, Depends, HTTPException, Request
from pydantic import BaseModel

from . import domains

logger = logging.getLogger(__name__)

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


class DomainsBody(BaseModel):
    origins: list[str]


def _verify_internal_token(request: Request) -> None:
    """Check the X-Internal-Token header against ROOHAI_INTERNAL_TOKEN."""
    expected = os.environ.get("ROOHAI_INTERNAL_TOKEN", "")
    if not expected:
        raise HTTPException(
            status_code=501,
            detail="Internal API not configured (ROOHAI_INTERNAL_TOKEN not set)",
        )
    token = request.headers.get("x-internal-token", "")
    if token != expected:
        raise HTTPException(status_code=403, detail="Invalid internal token")


@router.get("/domains", dependencies=[Depends(_verify_internal_token)])
async def list_domains():
    """List current whitelisted origins."""
    return {"origins": domains.list_origins()}


@router.post("/domains", dependencies=[Depends(_verify_internal_token)])
async def add_domains(body: DomainsBody):
    """Add origins to the whitelist."""
    updated = domains.add_origins(body.origins)
    return {"origins": updated}


@router.delete("/domains", dependencies=[Depends(_verify_internal_token)])
async def remove_domains(body: DomainsBody):
    """Remove origins from the whitelist."""
    updated = domains.remove_origins(body.origins)
    return {"origins": updated}


@router.put("/domains", dependencies=[Depends(_verify_internal_token)])
async def replace_domains(body: DomainsBody):
    """Replace the entire whitelist (force-refresh from platform DB)."""
    updated = domains.replace_origins(body.origins)
    return {"origins": updated}
