"""Birdcage MCP server — FastMCP entry point with lifespan management."""

import logging
import os
import sys
from contextlib import asynccontextmanager

from fastmcp import FastMCP

from mcbirdcage.state import BirdcageState

logger = logging.getLogger(__name__)


@asynccontextmanager
async def lifespan(server: FastMCP):
    """Server lifespan: configure state from environment, optionally pre-connect."""
    state = BirdcageState()

    demo_env = os.environ.get("BIRDCAGE_DEMO", "false").lower()
    state.demo_mode = demo_env in ("1", "true", "yes")
    state.serial_port = os.environ.get("BIRDCAGE_PORT", "/dev/ttyUSB0")
    state.firmware_name = os.environ.get("BIRDCAGE_FIRMWARE", "g2")
    craft_url = os.environ.get(
        "BIRDCAGE_CRAFT_URL", "https://space.warehack.ing"
    )

    if state.demo_mode:
        from birdcage.demo import DemoCraftClient, DemoDevice

        device = DemoDevice()
        device.connect()
        device.initialize()
        state.device = device
        state.craft_client = DemoCraftClient()
        state.connected = True
        logger.info("Demo mode: DemoDevice + DemoCraftClient ready")
    else:
        from birdcage.craft_client import CraftClient

        state.craft_client = CraftClient(base_url=craft_url)
        logger.info(
            "Hardware mode: use 'connect' tool to open serial port %s",
            state.serial_port,
        )

    try:
        yield state
    finally:
        if state.device is not None and hasattr(state.device, "disconnect"):
            try:
                state.device.disconnect()
            except Exception:
                logger.debug("Disconnect error during shutdown", exc_info=True)
        logger.info("Birdcage MCP server shut down")


mcp = FastMCP(
    "birdcage",
    instructions=(
        "Control a Winegard satellite dish (Carryout G2 / Trav'ler) for "
        "amateur radio satellite tracking. Provides motor control, signal "
        "measurement, firmware management, and orbital tracking via the "
        "Craft API."
    ),
    lifespan=lifespan,
)

# Register tool modules
from mcbirdcage import prompts, resources  # noqa: E402, F401
from mcbirdcage.tools import (  # noqa: E402
    connection,
    console,
    movement,
    satellite,
    signal,
    system,
)

connection.register(mcp)
movement.register(mcp)
signal.register(mcp)
system.register(mcp)
satellite.register(mcp)
console.register(mcp)
resources.register(mcp)
prompts.register(mcp)


def main():
    print("mcbirdcage v2026.02.17", file=sys.stderr)
    mcp.run()
