"""Wake-phrase CRUD endpoints.

Lets the dashboard edit the wake-phrase → action mapping stored in
data/wake_phrases.json.
"""

from __future__ import annotations

from typing import Optional

from fastapi import APIRouter, HTTPException
from pydantic import BaseModel

router = APIRouter()


class WakePhrasePayload(BaseModel):
    phrase: str
    action_id: str


class EnablePayload(BaseModel):
    phrase: str
    action_id: str
    enabled: bool


def _mgr():
    from Project.Sanad.main import wake_mgr
    if wake_mgr is None:
        raise HTTPException(503, "WakePhraseManager not initialized.")
    return wake_mgr


@router.get("/")
async def list_phrases():
    m = _mgr()
    return {
        "status": m.status(),
        "phrases": m.list(),
    }


@router.post("/")
async def add_phrase(payload: WakePhrasePayload):
    m = _mgr()
    try:
        entry = m.add(payload.phrase, payload.action_id)
    except ValueError as exc:
        raise HTTPException(400, str(exc))
    return {"ok": True, "entry": entry}


@router.delete("/")
async def remove_phrase(phrase: str, action_id: Optional[str] = None):
    m = _mgr()
    removed = m.remove(phrase, action_id)
    return {"ok": True, "removed": removed}


@router.post("/enable")
async def set_enabled(payload: EnablePayload):
    m = _mgr()
    ok = m.set_enabled(payload.phrase, payload.action_id, payload.enabled)
    if not ok:
        raise HTTPException(404, "phrase+action_id not found")
    return {"ok": True}


@router.get("/status")
async def status():
    return _mgr().status()
