"""MCP tool for listing individual custom report records.

This module implements the list_custom_reports tool following the service
layer pattern (ADR-006). The tool is a thin wrapper that:
1. Validates input with Pydantic
2. Extracts dependencies from server context (ADR-007)
3. Delegates to CustomReportService
4. Converts exceptions to user-friendly error format
"""

from typing import Annotated, Any, cast

from fastmcp import Context
from fastmcp.exceptions import ToolError
from pydantic import Field

from testio_mcp.server import ServerContext, mcp
from testio_mcp.services.custom_report_service import CustomReportService
from testio_mcp.utilities.parsing import parse_int_list_input, parse_list_input


@mcp.tool()
async def list_custom_reports(
    ctx: Context,
    test_ids: Annotated[
        list[int] | str | int,
        Field(
            description=(
                "Test IDs to list reports for (required). "
                "Accepts: list [147162, 147163], single int 147162, "
                "comma-separated string '147162,147163'"
            ),
            examples=[[147162], "147162", "147162,147163"],
        ),
    ],
    fields: Annotated[
        list[str] | str | None,
        Field(
            description=(
                "Specific report fields to include (defaults to all). "
                "Accepts: list ['accuracy', 'guardrails'], comma-separated 'accuracy,guardrails'"
            ),
            examples=[["accuracy", "guardrails"], "accuracy,guardrails"],
        ),
    ] = None,
    page: Annotated[
        int,
        Field(ge=1, description="Page number (1-indexed)"),
    ] = 1,
    per_page: Annotated[
        int,
        Field(ge=1, le=200, description="Items per page (default: 100, max: 200)"),
    ] = 100,
) -> dict[str, Any]:
    """List individual custom report records with pagination.

    Returns non-aggregated report rows (bug_id, title, report_fields) for
    building per-report prompt files. Same data source as
    get_custom_report_summary but returns rows instead of aggregating.

    Use get_custom_report_summary for aggregated statistics.
    Use list_custom_reports for individual report data.
    """
    # Parse inputs
    parsed_test_ids = parse_int_list_input(test_ids)
    if not parsed_test_ids:
        raise ToolError(
            "❌ test_ids is required\n"
            "ℹ️  Provide at least one test ID\n"
            "💡 Use list_tests to find test IDs"
        )

    parsed_fields = parse_list_input(fields)

    # Create service with managed AsyncSession lifecycle
    assert ctx.request_context is not None
    server_ctx = cast(ServerContext, ctx.request_context.lifespan_context)
    cache = server_ctx["cache"]

    async with cache.async_session_maker() as session:
        service = CustomReportService(
            session=session,
            customer_id=cache.customer_id,
        )

        try:
            return await service.list_reports(
                test_ids=parsed_test_ids,
                fields=parsed_fields,
                page=page,
                per_page=per_page,
            )
        except Exception as e:
            raise ToolError(
                f"❌ Unexpected error: {str(e)}\n"
                f"ℹ️  An error occurred while listing custom reports\n"
                f"💡 Please try again or contact support if the problem persists"
            ) from e
