"""Financial reporting tools."""

from __future__ import annotations

from typing import Any

from fastmcp.exceptions import ToolError
from mcp.types import ToolAnnotations

from mcp_eregistrations_ds.ds_client import (
    DSClient,
    DSClientError,
    DSPermissionError,
    translate_error,
)
from mcp_eregistrations_ds.server import mcp


@mcp.tool(annotations=ToolAnnotations(readOnlyHint=True))
async def financial_report_data(
    from_date: str,
    to_date: str,
    service: str | None = None,
    is_paid_digitally: bool | None = None,
    instance: str | None = None,
) -> dict[str, Any]:
    """Query financial/revenue report data.

    Args:
        from_date: Start date (YYYY-MM-DD).
        to_date: End date (YYYY-MM-DD).
        service: Filter by service name.
        is_paid_digitally: Filter by digital payment flag.
        instance: Instance profile name.

    Returns:
        dict with revenue data, totals, breakdowns.
    """
    params: dict[str, Any] = {"fromDate": from_date, "toDate": to_date}
    if service:
        params["service"] = service
    if is_paid_digitally is not None:
        params["isPayedDigitally"] = str(is_paid_digitally).lower()

    try:
        async with DSClient.for_instance(instance) as client:
            try:
                result: dict[str, Any] = await client.get(
                    "/api/v1/financial-report/data/", params=params
                )
            except DSPermissionError:
                raise ToolError(
                    "Financial report access denied. Requires a Camunda role "
                    "with allowAccessToFinancialReports=True (not just is_staff)."
                )
            return result
    except DSClientError as e:
        raise translate_error(e, resource_type="financial_report") from e


@mcp.tool(annotations=ToolAnnotations(readOnlyHint=True))
async def financial_report_export(
    from_date: str,
    to_date: str,
    format: str = "excel",
    service: str | None = None,
    instance: str | None = None,
) -> dict[str, Any]:
    """Export financial report as Excel or PDF.

    Args:
        from_date: Start date (YYYY-MM-DD).
        to_date: End date (YYYY-MM-DD).
        format: Export format — "excel" or "pdf" (default: excel).
        service: Filter by service name.
        instance: Instance profile name.

    Returns:
        dict with exported (bool), format, date range.
    """
    params: dict[str, Any] = {"fromDate": from_date, "toDate": to_date}
    if service:
        params["service"] = service

    fmt = "excel" if format not in ("excel", "pdf") else format

    try:
        async with DSClient.for_instance(instance) as client:
            try:
                await client.get(
                    f"/api/v1/financial-report/export/{fmt}/", params=params
                )
            except DSPermissionError:
                raise ToolError(
                    "Financial report export denied. Requires a Camunda role "
                    "with allowAccessToFinancialReports=True (not just is_staff)."
                )
    except DSClientError as e:
        raise translate_error(e, resource_type="financial_report_export") from e

    return {
        "exported": True,
        "format": fmt,
        "from_date": from_date,
        "to_date": to_date,
    }
