from __future__ import annotations

from typing import TYPE_CHECKING

from fastapi import APIRouter, HTTPException
from pydantic import BaseModel

if TYPE_CHECKING:
    from niannian.client import NianNian


class PairDeviceBody(BaseModel):
    token: str
    name: str = "mobile"


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

    @router.post("/pairing")
    def create_pairing(host: str | None = None):
        base = host or f"http://127.0.0.1:18765"
        return nn.bridge_pairing.create_pairing(host=base).to_dict()

    @router.post("/devices")
    def register_device(payload: PairDeviceBody):
        try:
            return nn.bridge_pairing.register_device(payload.token, name=payload.name)
        except ValueError:
            raise HTTPException(status_code=400, detail={"code": "invalid_token"}) from None

    @router.get("/devices")
    def list_devices():
        return {"devices": nn.bridge_pairing.list_devices()}

    return router
