from __future__ import annotations

from typing import TYPE_CHECKING, Any

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

if TYPE_CHECKING:
    from niannian.client import NianNian


class DeviceExecuteBody(BaseModel):
    type: str
    params: dict[str, Any] = Field(default_factory=dict)
    confirmed: bool = False


def create_device_router(nn: NianNian) -> APIRouter:
    router = APIRouter(prefix="/v1/device", tags=["device"])

    @router.post("/execute")
    def execute_device(payload: DeviceExecuteBody):
        from niannian.device.gateway import MacRequiredError, NeedConfirmationError

        action = {"type": payload.type, "params": payload.params}
        try:
            result = nn.device.execute(action, confirmed=payload.confirmed)
            return result.to_dict()
        except MacRequiredError:
            raise HTTPException(status_code=503, detail={"code": "mac_required"}) from None
        except NeedConfirmationError as e:
            raise HTTPException(
                status_code=409,
                detail={"code": "need_confirmation", "action": e.action},
            ) from e

    return router
