from __future__ import annotations

from typing import TYPE_CHECKING, Any

from aicd.config import save_config
from aicd.config_settings import apply_nested_settings_patch, format_settings_summary

if TYPE_CHECKING:
    from aicd.agent.tool_router import ToolRouter


def _agent_settings_update(router: ToolRouter, args: dict[str, Any]) -> dict[str, Any]:
    patch = args.get("patch")
    if patch is None:
        return {
            "ok": True,
            "message": "no patch; current summary",
            "summary": format_settings_summary(router._cfg),
        }
    if not isinstance(patch, dict):
        return {"ok": False, "error": "patch must be an object with optional llm / agent keys"}
    ok, msg = apply_nested_settings_patch(router._cfg, patch)
    if not ok:
        return {"ok": False, "error": msg}
    if bool(args.get("persist", True)):
        save_config(router._layout["config"], router._cfg)
    return {
        "ok": True,
        "message": msg,
        "summary": format_settings_summary(router._cfg),
        "persisted": bool(args.get("persist", True)),
    }


HANDLERS: dict[str, Any] = {
    "agent_settings_update": _agent_settings_update,
}
