"""FastMCP server — thin tool wrappers over controller methods.

Tools are minimal: validate args, call controller, return result.
All business logic lives in controllers.py.

Usage:
    # stdio (for Claude Code)
    platoon mcp

    # or directly
    python -m platoon.mcp.server
"""

from __future__ import annotations

from typing import Any, Optional

from fastmcp import FastMCP

from platoon.mcp import controllers

MCP_INSTRUCTIONS = """Platoon is an AI training suite for commerce analytics.

Available tools:
- **read_file**: Load CSV or text files. Use this first to inspect data.
- **forecast**: Run demand forecasting on time series CSV data.
- **optimize**: Run inventory optimization (EOQ, safety stock, reorder points, ABC).

Typical workflow:
1. read_file to inspect the CSV columns and sample rows
2. forecast or optimize with the file path and relevant parameters
"""


def create_mcp_server() -> FastMCP:
    """Create the Platoon MCP server with learning tools."""
    mcp = FastMCP(name="platoon", instructions=MCP_INSTRUCTIONS)

    @mcp.tool()
    async def read_file(path: str, head: int = 0) -> dict[str, Any]:
        """Read a CSV or text file. Returns rows (for CSV) or text content.

        Args:
            path: File path to read.
            head: If > 0, return only the first N rows/lines.
        """
        return controllers.read_file(path, head=head)

    @mcp.tool()
    async def forecast(
        data_path: str,
        product_id: Optional[str] = None,
        horizon: int = 14,
        method: str = "auto",
        season_length: int = 7,
        holdout: int = 30,
    ) -> dict[str, Any]:
        """Run demand forecasting on a CSV time series.

        CSV must have columns: date, product_id, units_sold.
        Returns forecast values, confidence intervals, trend, seasonality, and accuracy (MAE).

        Args:
            data_path: Path to daily demand CSV file.
            product_id: Which product to forecast. Picks highest-volume if omitted.
            horizon: Days ahead to forecast (default 14). Must be >= 1.
            method: auto, moving_average, exponential_smoothing, croston, arima, ets, theta.
            season_length: Seasonal period in days (default 7).
            holdout: Days to hold out for accuracy eval (default 30).
        """
        return controllers.forecast(
            data_path, product_id=product_id, horizon=horizon,
            method=method, season_length=season_length, holdout=holdout,
        )

    @mcp.tool()
    async def optimize(
        data_path: str,
        product_id: Optional[str] = None,
        orders_path: Optional[str] = None,
        inventory_path: Optional[str] = None,
        service_level: float = 0.95,
    ) -> dict[str, Any]:
        """Run inventory optimization on product data.

        Computes EOQ, safety stock, reorder point, ABC class, stockout risk,
        plus price, cost, daily_revenue, restock_cost, and days_of_stock
        so the agent can compute ROI and revenue-at-risk without extra calls.

        Args:
            data_path: Path to products CSV (product_id, sku, cost, price, base_daily_demand, lead_time_days).
            product_id: Analyze a single product. If omitted, analyzes all.
            orders_path: Optional orders CSV for ABC classification.
            inventory_path: Optional inventory CSV for current stock levels.
            service_level: Target service level (0-1 exclusive, default 0.95).
        """
        return controllers.optimize(
            data_path, product_id=product_id, orders_path=orders_path,
            inventory_path=inventory_path, service_level=service_level,
        )

    return mcp


if __name__ == "__main__":
    import asyncio
    mcp = create_mcp_server()
    asyncio.run(mcp.run_async(transport="stdio"))
