from typing import Any

from fastapi import APIRouter, Header, HTTPException, Query, Request

from config import settings
from connectors.registry import connector_registry

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


def _check_secret(
    secret_query: str | None,
    secret_header: str | None,
) -> None:
    provided = secret_query or secret_header
    if not provided or provided != settings.webhook_secret:
        raise HTTPException(status_code=401, detail="Invalid webhook secret")


async def _read_payload(request: Request) -> dict[str, Any]:
    content_type = request.headers.get("content-type", "")
    if "application/json" in content_type:
        payload = await request.json()
    else:
        raw = (await request.body()).decode("utf-8", errors="replace").strip()
        payload = {"comment": raw, "ticker": "UNKNOWN", "action": "buy"}

    if not isinstance(payload, dict):
        raise HTTPException(status_code=422, detail="Expected JSON object")
    return payload


@router.post("/{platform}")
async def platform_webhook(
    platform: str,
    request: Request,
    secret: str | None = Query(default=None),
    x_webhook_secret: str | None = Header(default=None, alias="X-Webhook-Secret"),
) -> dict[str, Any]:
    """
    Webhook entrant par plateforme.

    Plateforme active : ninjatrader.
    """
    _check_secret(secret, x_webhook_secret)

    connector = connector_registry.get(platform)
    if connector is None:
        raise HTTPException(status_code=404, detail=f"Unknown platform: {platform}")

    payload = await _read_payload(request)

    try:
        return await connector.handle_inbound(payload)
    except ValueError as exc:
        raise HTTPException(status_code=422, detail=str(exc)) from exc
