"""MCP resources: portfolio state and risk limits."""

from __future__ import annotations

from typing import Any

from liquidtrading.errors import LiquidError
from liquid_mcp.client_manager import get_client
from liquid_mcp.config import get_config
from liquid_mcp.guardrails import get_loss_tracker
from liquid_mcp.serializers import to_dict
from liquid_mcp.server import mcp


@mcp.resource("liquid://portfolio")
def portfolio_resource() -> dict[str, Any]:
    """Current portfolio: positions, equity, margin, unrealized PnL."""
    client = get_client(get_config())
    account = to_dict(client.get_account())
    positions = to_dict(client.get_positions())
    return {
        "account": account,
        "positions": positions,
    }


@mcp.resource("liquid://risk")
def risk_resource() -> dict[str, Any]:
    """Current risk state: daily loss, max order limit, exposure."""
    cfg = get_config()
    tracker = get_loss_tracker(cfg.daily_loss_limit)
    result: dict[str, Any] = {
        "max_order_usd": cfg.max_order_usd,
        "daily_loss_limit": cfg.daily_loss_limit,
        "daily_loss_used": tracker.cumulative_loss,
        "daily_loss_remaining": tracker.remaining,
    }
    try:
        client = get_client(cfg)
        positions = client.get_positions()
        total_exposure = sum(abs(p.size) for p in positions)
        result["positions_count"] = len(positions)
        result["total_exposure"] = total_exposure
    except LiquidError:
        result["positions_count"] = None
        result["total_exposure"] = None
        result["error_hint"] = "Could not fetch positions. Check API credentials."
    return result
