"""
Routes pour la configuration
"""
from fastapi import APIRouter, HTTPException
from pydantic import BaseModel
import yaml
from backend.app.core.config import config_manager

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

@router.get("/ui")
async def get_ui_config():
    """Récupérer la configuration UI"""
    config = config_manager.config
    return {
        "cell_size": config.ui.cell_size,
        "font_size": config.ui.font_size,
        "cell_gap": config.ui.cell_gap,
        "offline_transparency": config.ui.offline_transparency,
        "show_mac": config.ui.show_mac,
        "show_vendor": config.ui.show_vendor,
        "architecture_title_font_size": config.ui.architecture_title_font_size
    }

@router.post("/reload")
async def reload_config():
    """Recharger la configuration depuis le fichier config.yaml"""
    try:
        config = config_manager.reload_config()
        return {
            "success": True,
            "message": "Configuration rechargée avec succès",
            "ui": {
                "cell_size": config.ui.cell_size,
                "font_size": config.ui.font_size,
            "cell_gap": config.ui.cell_gap,
            "offline_transparency": config.ui.offline_transparency,
            "show_mac": config.ui.show_mac,
            "show_vendor": config.ui.show_vendor,
            "architecture_title_font_size": config.ui.architecture_title_font_size
            }
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Erreur rechargement config: {str(e)}")


class UIConfigUpdate(BaseModel):
    architecture_title_font_size: int


@router.post("/ui")
async def update_ui_config(payload: UIConfigUpdate):
    """Mettre à jour la configuration UI"""
    config_path = "./config.yaml"
    try:
        with open(config_path, "r", encoding="utf-8") as f:
            yaml_data = yaml.safe_load(f) or {}

        if "ui" not in yaml_data or yaml_data["ui"] is None:
            yaml_data["ui"] = {}

        yaml_data["ui"]["architecture_title_font_size"] = int(payload.architecture_title_font_size)

        with open(config_path, "w", encoding="utf-8") as f:
            yaml.safe_dump(yaml_data, f, allow_unicode=True, sort_keys=False)

        config = config_manager.reload_config()
        return {
            "message": "Configuration UI mise à jour",
            "architecture_title_font_size": config.ui.architecture_title_font_size
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Erreur mise à jour config UI: {str(e)}")
