"""DICOM tree dump tool."""

import asyncio
import json
from pathlib import Path

import pydicom
from pydicom.errors import InvalidDicomError
from mcp.types import ToolAnnotations

from dicom_mcp.server import mcp
from dicom_mcp.constants import ResponseFormat
from dicom_mcp.helpers.tree import _build_tree_text, _build_tree_json


@mcp.tool(
    name="dicom_dump_tree",
    annotations=ToolAnnotations(
        title="Dump DICOM Tree Structure",
        readOnlyHint=True,
        destructiveHint=False,
        idempotentHint=True,
        openWorldHint=False,
    ),
)
async def dicom_dump_tree(
    file_path: str,
    max_depth: int = 10,
    show_private: bool = True,
    response_format: ResponseFormat = ResponseFormat.MARKDOWN,
) -> str:
    """Display the full hierarchical structure of a DICOM file.

    Recursively traverses the DICOM dataset including nested sequences,
    producing an indented tree view. Useful for deep inspection of DICOM
    structure, discovering nested sequence contents, and understanding
    how data is organized across different manufacturers.

    Args:
        file_path: Path to a DICOM file
        max_depth: Maximum recursion depth for nested sequences (default 10)
        show_private: Include private tags in the output (default True)
        response_format: Output format (markdown or json)
    """
    try:
        fp = Path(file_path)
        if not fp.exists():
            return f"Error: File not found: {file_path}"

        ds = await asyncio.to_thread(pydicom.dcmread, fp, stop_before_pixels=True)

        if response_format == ResponseFormat.JSON:
            tree = _build_tree_json(
                ds,
                max_depth=max_depth,
                show_private=show_private,
            )
            result = {
                "file": fp.name,
                "element_count": len([e for e in ds if e.tag != (0x7FE0, 0x0010)]),
                "max_depth": max_depth,
                "show_private": show_private,
                "tree": tree,
            }
            return json.dumps(result, indent=2)
        else:
            lines = _build_tree_text(
                ds,
                max_depth=max_depth,
                show_private=show_private,
            )
            header = [
                f"# DICOM Tree: {fp.name}\n",
                f"**Max depth**: {max_depth}",
                f"**Show private tags**: {show_private}\n",
                "```",
            ]
            footer = ["```"]
            return "\n".join(header + lines + footer)

    except InvalidDicomError:
        return f"Error: Not a valid DICOM file: {file_path}"
    except Exception as e:
        return f"Error dumping DICOM tree: {str(e)}"
