"""ERP → FastAPI Command API.

Called by ERP PHP when a tank is allocated to a BASF job.
Validates + publishes `fastlane.tank.allocate.requested` to Kafka.
"""
from fastapi import APIRouter, Header, HTTPException, status

from ..config import get_settings
from pprint import pprint
from ..kafka_client import get_producer
from ..logger import get_logger
from ..schemas import TankAllocationCommand, TankAllocationRequestedEvent
from .debug import record_allocation

router = APIRouter(prefix="", tags=["commands"])
log = get_logger(__name__)


def _check_api_key(x_api_key: str | None) -> None:
    settings = get_settings()
    if not x_api_key or x_api_key != settings.command_api_key:
        raise HTTPException(status_code=401, detail="Invalid API key")


@router.post("/tank-allocation", status_code=status.HTTP_202_ACCEPTED)
async def request_tank_allocation(
    cmd: TankAllocationCommand,
    x_api_key: str | None = Header(default=None, alias="X-API-Key"),
) -> dict:
    """Accept a tank-allocation command from ERP and emit a Kafka event."""
    _check_api_key(x_api_key)
    log.info("↘ ERP tank-allocation received: %s", cmd.model_dump())
    event = TankAllocationRequestedEvent(**cmd.model_dump())

    producer = await get_producer()
    settings = get_settings()
    await producer.publish(
        topic=settings.topic_allocate_requested,
        key=f"{cmd.job_id}:{cmd.licence_number}",
        value=event.model_dump(mode="json"),
    )

    log.info(
        "Accepted tank allocation job=%s tank=%s plate=%s event=%s",
        cmd.job_id, cmd.tank_id, cmd.licence_number, event.event_id,
    )
    record_allocation(cmd.model_dump(), str(event.event_id))
    return {
        "accepted": True,
        "event_id": event.event_id,
        "status": "pending",
    }
