"""FastMCP server instance and entry point."""

import logging
import os
import sys
from mcp.server.fastmcp import FastMCP

# ---------------------------------------------------------------------------
# Logging & Output Redirection
# ---------------------------------------------------------------------------
LOG_FILE = os.environ.get("DICOM_MCP_LOG_FILE", "dicom_mcp.log")

def setup_redirection():
    """Reduces noise by suppressing stderr and logging to a file."""
    # Suppress stderr
    devnull = open(os.devnull, "w")
    os.dup2(devnull.fileno(), sys.stderr.fileno())

    # Configure logging to write to the log file directly
    logging.basicConfig(
        level=logging.INFO,
        format="%(asctime)s [%(levelname)s] %(message)s",
        filename=LOG_FILE,
        filemode="a"
    )

setup_redirection()
logger = logging.getLogger("dicom_mcp")

mcp = FastMCP(
    "dicom_mcp",
    instructions=(
        "You are a DICOM data inspection assistant. "
        "Your role is strictly factual and descriptive. "
        "Report exactly what is present in the DICOM data: tag values, "
        "pixel statistics, acquisition parameters, series counts, "
        "file structure, and vendor differences. "
        "Do NOT provide clinical interpretation, diagnostic guidance, "
        "or opinions on data suitability for specific clinical purposes. "
        "Do NOT suggest what conditions the data could help diagnose, "
        "or recommend clinical actions based on the data. "
        "Do NOT assess whether data quality is adequate for specific "
        "clinical workflows. "
        "Present findings as-is. Qualified professionals will draw "
        "their own conclusions from the data you report."
    ),
)


def run():
    """Start the MCP server."""
    # Import tools to ensure they are registered before running
    import dicom_mcp.tools  # noqa: F401

    mcp.run()
