"""Macro recording and playback endpoints."""

from __future__ import annotations

from fastapi import APIRouter, HTTPException
from pydantic import BaseModel

router = APIRouter()


class MacroName(BaseModel):
    name: str


@router.get("/")
async def list_macros():
    from Project.Sanad.main import macro_play
    if macro_play is None:
        return {"macros": []}
    return {"macros": macro_play.list_macros()}


@router.get("/status")
async def macro_status():
    from Project.Sanad.main import macro_rec, macro_play
    return {
        "recorder": macro_rec.status() if macro_rec else {},
        "player": macro_play.status() if macro_play else {},
    }


@router.post("/record/start")
async def start_recording(payload: MacroName):
    from Project.Sanad.main import macro_rec
    if macro_rec is None:
        raise HTTPException(503, "Macro recorder not available.")
    return macro_rec.start(payload.name)


@router.post("/record/stop")
async def stop_recording():
    import asyncio
    from Project.Sanad.main import macro_rec
    if macro_rec is None:
        raise HTTPException(503, "Macro recorder not available.")
    return await asyncio.to_thread(macro_rec.stop)


@router.post("/play")
async def play_macro(payload: MacroName):
    from Project.Sanad.main import brain
    return await brain.play_macro(payload.name)


@router.post("/stop")
async def stop_macro():
    from Project.Sanad.main import macro_play
    if macro_play:
        macro_play.stop()
    return {"ok": True}
