from __future__ import annotations

from fastapi import APIRouter, Body, HTTPException

from backend.app.core.config import BackendConfig, CONFIG_PATH, load_config

router = APIRouter(prefix="/config", tags=["config"])


@router.get("/backend", response_model=BackendConfig)
def read_backend_config() -> BackendConfig:
    # expose la configuration backend en lecture seule
    return load_config()


@router.put("/backend", response_model=BackendConfig)
def update_backend_config(payload: dict = Body(...)) -> BackendConfig:
    current = load_config()
    try:
        # validation via Pydantic avant écriture
        updated = current.copy(update=payload)
        CONFIG_PATH.write_text(updated.json(indent=2, ensure_ascii=False))
        load_config.cache_clear()
        return load_config()
    except Exception as exc:  # pragma: no cover
        raise HTTPException(status_code=400, detail=str(exc))
