"""REST endpoints for the dashboard setup checklist."""

from __future__ import annotations

from typing import Any

from fastapi import APIRouter, HTTPException
from pydantic import BaseModel

from proxym.observability import log_call

router = APIRouter(tags=["setup"])


class ToggleSetupStepReq(BaseModel):
    completed: bool | None = None


def _cmd_bus():
    from proxym.domain.setup import get_command_bus
    return get_command_bus()


def _qry_bus():
    from proxym.domain.setup import get_query_bus
    return get_query_bus()


@router.get("/setup")
async def get_setup_state() -> dict[str, Any]:
    """Return the current setup checklist snapshot."""
    from proxym.domain.queries import GetSetupChecklistQuery

    return await _qry_bus().dispatch(GetSetupChecklistQuery())


@router.post("/setup/steps/{step_id}/toggle")
@log_call(level="info")
async def toggle_setup_step(step_id: str, req: ToggleSetupStepReq | None = None) -> dict[str, Any]:
    """Mark a setup checklist step complete/incomplete."""
    from proxym.domain.commands import ToggleSetupStepCommand

    cmd = ToggleSetupStepCommand(
        actor="api",
        step_id=step_id,
        completed=req.completed if req is not None else None,
    )
    try:
        return await _cmd_bus().dispatch(cmd)
    except ValueError as exc:
        raise HTTPException(status_code=400, detail=str(exc)) from exc


@router.post("/setup/reset")
@log_call(level="info")
async def reset_setup() -> dict[str, Any]:
    """Clear the setup checklist state."""
    from proxym.domain.commands import ResetSetupChecklistCommand

    try:
        return await _cmd_bus().dispatch(ResetSetupChecklistCommand(actor="api"))
    except ValueError as exc:
        raise HTTPException(status_code=400, detail=str(exc)) from exc
