# -*- coding: utf-8 -*-
"""FastMCP 服务入口：只做装配（校验入参 -> 调 core -> 返回 dict），不含业务逻辑。

启动：fastmcp dev src/a207_meal_plan_mcp/server.py
M7 营养师可调（生成食谱）；生成结果回写 M3 由上层编排负责。
"""
from __future__ import annotations

from typing import Any, Dict, List, Optional

from fastmcp import FastMCP

from . import core
from .models import MealPlanRequest, PlanNutrientsRequest

mcp = FastMCP("a207-meal-plan-mcp")


def _invalid(exc: Exception) -> dict[str, Any]:
    return {"ok": False, "error": "INVALID_INPUT", "detail": str(exc)}


@mcp.tool
def generate_meal_plan(
    target_energy_kcal: float,
    target_protein_g: float,
    target_k_mg: float,
    target_p_mg: float,
    target_na_mg: float,
    days: int = 7,
    vegetarian: bool = False,
    exclude_foods: Optional[List[str]] = None,
) -> dict[str, Any]:
    """按 PRNT 目标生成多日食谱（3 餐 + 加餐），返回餐次明细、每日汇总与达成率。营养师调用。"""
    try:
        req: MealPlanRequest = MealPlanRequest(
            target_energy_kcal=target_energy_kcal,
            target_protein_g=target_protein_g,
            target_k_mg=target_k_mg,
            target_p_mg=target_p_mg,
            target_na_mg=target_na_mg,
            days=days,
            vegetarian=vegetarian,
            exclude_foods=exclude_foods,
        )
        res = core.generate_meal_plan(
            target_energy_kcal=req.target_energy_kcal,
            target_protein_g=req.target_protein_g,
            target_k_mg=req.target_k_mg,
            target_p_mg=req.target_p_mg,
            target_na_mg=req.target_na_mg,
            days=req.days,
            vegetarian=req.vegetarian,
            exclude_foods=req.exclude_foods,
        )
        return {"ok": True, "data": res}
    except Exception as exc:  # noqa: BLE001
        return _invalid(exc)


@mcp.tool
def get_meal_plan_nutrients(plan: Dict[str, Any]) -> dict[str, Any]:
    """从已生成 plan 重新汇总整体平均每日营养素（校验用）。"""
    try:
        req: PlanNutrientsRequest = PlanNutrientsRequest(plan=plan)
        res = core.get_meal_plan_nutrients(req.plan)
        return {"ok": True, "data": res}
    except Exception as exc:  # noqa: BLE001
        return _invalid(exc)
