"""The API the Mamadachi itself talks to. One endpoint, one round trip per wake: upload queued presses + telemetry, get back the button layout and what to draw.""" from typing import Annotated from fastapi import APIRouter, Depends, Header, HTTPException from sqlalchemy.exc import IntegrityError from sqlalchemy.orm import Session from ..db import get_db from ..models import Device from ..schemas import SyncRequest, SyncResponse from ..services.ingest import IngestResult, device_for_token, ingest, sync_response router = APIRouter(prefix="/api/v1/device", tags=["device"]) def current_device( db: Annotated[Session, Depends(get_db)], authorization: Annotated[str | None, Header(description="Bearer mmd_...")] = None, ) -> Device: token = "" if authorization and authorization.lower().startswith("bearer "): token = authorization[7:].strip() device = device_for_token(db, token) if device is None: raise HTTPException( status_code=401, detail="Unknown or revoked device token.", headers={"WWW-Authenticate": "Bearer"}, ) return device @router.post("/sync", response_model=SyncResponse) def sync( req: SyncRequest, device: Annotated[Device, Depends(current_device)], db: Annotated[Session, Depends(get_db)], ) -> SyncResponse: """Upload presses and telemetry; receive config and display status. **200** = every event in `events` is stored (new or already known): delete them from the device. Any other status: keep them and retry with backoff. Send at most 500 events per request; if more are queued, sync again straight away (`queue_len` tells the server more are coming). """ try: result = ingest(db, device, req) except IntegrityError: # Two uploads of the same batch raced each other. Nothing is lost: # the device gets a 409, keeps the batch, and the retry is a no-op. db.rollback() raise HTTPException(status_code=409, detail="Concurrent upload, retry.") from None return sync_response(db, result) @router.get("/config", response_model=SyncResponse) def config( device: Annotated[Device, Depends(current_device)], db: Annotated[Session, Depends(get_db)], ) -> SyncResponse: """Same response as an empty sync, without recording a report. Handy for testing the token and the display from a laptop.""" return sync_response(db, IngestResult(0, 0, 0, None, False, None))