"""
DataDocked MCP Server
Maritime data API integration for AI assistants
"""

import os
import asyncio
from datetime import datetime, timedelta
from typing import Any

from mcp.server import Server
from mcp.server.stdio import stdio_server
from mcp.types import (
    Tool,
    TextContent,
    Resource,
)

from .api.client import DataDockedClient, CREDIT_COSTS
from .utils import formatters as fmt

# Load settings
API_KEY = os.environ.get("DATADOCKED_API_KEY", "")
SHOW_COST = os.environ.get("DATADOCKED_SHOW_COST", "true").lower() != "false"

# Initialize server
server = Server("datadocked")

# Client will be initialized on first use
_client: DataDockedClient | None = None


def get_client() -> DataDockedClient:
    """Get or create the API client"""
    global _client
    if _client is None:
        if not API_KEY:
            raise ValueError(
                "DATADOCKED_API_KEY environment variable is required. "
                "Get your API key at https://datadocked.com"
            )
        _client = DataDockedClient(API_KEY, SHOW_COST)
    return _client


# ============================================
# TOOLS
# ============================================

@server.list_tools()
async def list_tools() -> list[Tool]:
    """List available tools"""
    return [
        # === BASIC TOOLS ===
        Tool(
            name="track_vessel",
            description="Get real-time position, speed, course, heading, destination, and ETA for a vessel. Cost: 1 credit.",
            inputSchema={
                "type": "object",
                "properties": {
                    "identifier": {
                        "type": "string",
                        "description": "IMO number (7 digits) or MMSI (9 digits) of the vessel",
                    },
                },
                "required": ["identifier"],
            },
        ),
        Tool(
            name="track_vessels_bulk",
            description="Track up to 50 vessels at once. Returns positions for all specified vessels. Cost: 1 credit per vessel.",
            inputSchema={
                "type": "object",
                "properties": {
                    "identifiers": {
                        "type": "array",
                        "items": {"type": "string"},
                        "description": "Array of IMO or MMSI identifiers (max 50)",
                    },
                },
                "required": ["identifiers"],
            },
        ),
        Tool(
            name="get_vessel_history",
            description="Get historical positions for a vessel. Up to 2 years of data. Cost: 5 credits per day of history.",
            inputSchema={
                "type": "object",
                "properties": {
                    "identifier": {"type": "string", "description": "IMO or MMSI of the vessel"},
                    "start_date": {"type": "string", "description": "Start date in YYYY-MM-DD format"},
                    "end_date": {"type": "string", "description": "End date in YYYY-MM-DD format"},
                },
                "required": ["identifier", "start_date", "end_date"],
            },
        ),
        Tool(
            name="search_vessels_by_area",
            description="Find all vessels within a geographic bounding box. Cost: 10 credits.",
            inputSchema={
                "type": "object",
                "properties": {
                    "lat1": {"type": "number", "description": "Southwest corner latitude"},
                    "lon1": {"type": "number", "description": "Southwest corner longitude"},
                    "lat2": {"type": "number", "description": "Northeast corner latitude"},
                    "lon2": {"type": "number", "description": "Northeast corner longitude"},
                    "vessel_type": {"type": "string", "description": "Optional: Filter by vessel type"},
                },
                "required": ["lat1", "lon1", "lat2", "lon2"],
            },
        ),
        Tool(
            name="get_vessel_details",
            description="Get full vessel profile including type, flag, build year, tonnage, dimensions. Cost: 5 credits.",
            inputSchema={
                "type": "object",
                "properties": {
                    "imo": {"type": "string", "description": "IMO number of the vessel (7 digits)"},
                },
                "required": ["imo"],
            },
        ),
        Tool(
            name="get_vessel_specs",
            description="Get vessel particulars: length, beam, depth, draft, tonnage, TEU capacity. Cost: 3 credits.",
            inputSchema={
                "type": "object",
                "properties": {
                    "imo": {"type": "string", "description": "IMO number of the vessel"},
                },
                "required": ["imo"],
            },
        ),
        Tool(
            name="get_vessel_engine",
            description="Get engine specifications: type, power, fuel type, service speed. Cost: 3 credits.",
            inputSchema={
                "type": "object",
                "properties": {
                    "imo": {"type": "string", "description": "IMO number of the vessel"},
                },
                "required": ["imo"],
            },
        ),
        Tool(
            name="get_vessel_management",
            description="Get ownership and management info: owner, operator, manager, P&I club, class. Cost: 3 credits.",
            inputSchema={
                "type": "object",
                "properties": {
                    "imo": {"type": "string", "description": "IMO number of the vessel"},
                },
                "required": ["imo"],
            },
        ),
        Tool(
            name="get_port_calls",
            description="Get port call history for a vessel: arrivals, departures, duration. Cost: 1 credit.",
            inputSchema={
                "type": "object",
                "properties": {
                    "identifier": {"type": "string", "description": "IMO or MMSI of the vessel"},
                },
                "required": ["identifier"],
            },
        ),
        Tool(
            name="get_port_traffic",
            description="Get port traffic: current arrivals, departures, and expected vessels. Cost: 5 credits.",
            inputSchema={
                "type": "object",
                "properties": {
                    "port_code": {"type": "string", "description": "UN/LOCODE port code (e.g., SGSIN for Singapore)"},
                },
                "required": ["port_code"],
            },
        ),
        Tool(
            name="get_psc_inspections",
            description="Get Port State Control inspection history: deficiencies, detentions. Cost: 3 credits.",
            inputSchema={
                "type": "object",
                "properties": {
                    "imo": {"type": "string", "description": "IMO number of the vessel"},
                },
                "required": ["imo"],
            },
        ),
        Tool(
            name="get_vessel_weather",
            description="Get current weather conditions at a location: wind, waves, visibility. Cost: 2 credits.",
            inputSchema={
                "type": "object",
                "properties": {
                    "latitude": {"type": "number", "description": "Latitude of the location"},
                    "longitude": {"type": "number", "description": "Longitude of the location"},
                },
                "required": ["latitude", "longitude"],
            },
        ),
        # === COMPOUND TOOLS ===
        Tool(
            name="vessel_intelligence_report",
            description="Generate a comprehensive vessel intelligence report. Combines: location + details + specs + engine + management + port calls + PSC inspections. Cost: ~18 credits.",
            inputSchema={
                "type": "object",
                "properties": {
                    "imo": {"type": "string", "description": "IMO number of the vessel"},
                },
                "required": ["imo"],
            },
        ),
        Tool(
            name="fleet_dashboard",
            description="Get a fleet status dashboard with positions and details for multiple vessels. Cost: ~3 credits per vessel.",
            inputSchema={
                "type": "object",
                "properties": {
                    "identifiers": {
                        "type": "array",
                        "items": {"type": "string"},
                        "description": "Array of IMO or MMSI identifiers",
                    },
                },
                "required": ["identifiers"],
            },
        ),
        Tool(
            name="voyage_analysis",
            description="Analyze a vessel's current voyage: position, recent history, port calls, weather conditions. Cost: ~13 credits.",
            inputSchema={
                "type": "object",
                "properties": {
                    "identifier": {"type": "string", "description": "IMO or MMSI of the vessel"},
                },
                "required": ["identifier"],
            },
        ),
        Tool(
            name="risk_assessment",
            description="Generate a risk assessment for a vessel: PSC history + management + recent movements. Cost: ~12 credits.",
            inputSchema={
                "type": "object",
                "properties": {
                    "imo": {"type": "string", "description": "IMO number of the vessel"},
                },
                "required": ["imo"],
            },
        ),
        Tool(
            name="area_intelligence",
            description="Get intelligence on all vessels in an area with full profiles for each. Cost: 10 + 5 per vessel.",
            inputSchema={
                "type": "object",
                "properties": {
                    "lat1": {"type": "number", "description": "Southwest latitude"},
                    "lon1": {"type": "number", "description": "Southwest longitude"},
                    "lat2": {"type": "number", "description": "Northeast latitude"},
                    "lon2": {"type": "number", "description": "Northeast longitude"},
                    "vessel_type": {"type": "string", "description": "Optional vessel type filter"},
                    "max_vessels": {"type": "number", "description": "Max vessels to get details for (default 10)"},
                },
                "required": ["lat1", "lon1", "lat2", "lon2"],
            },
        ),
    ]


@server.call_tool()
async def call_tool(name: str, arguments: dict[str, Any]) -> list[TextContent]:
    """Handle tool calls"""
    client = get_client()

    try:
        # === BASIC TOOLS ===
        if name == "track_vessel":
            identifier = arguments["identifier"]
            cost = client.estimate_cost("get-vessel-location")
            result = fmt.format_credit_estimate("Track vessel", cost) if SHOW_COST else ""

            response = await client.get_vessel_location(identifier)
            result += fmt.format_vessel_location(response["detail"])
            result += fmt.format_credits_used(response.get("credits_used", cost), response.get("credits_remaining"))

            return [TextContent(type="text", text=result)]

        elif name == "track_vessels_bulk":
            identifiers = arguments["identifiers"]
            cost = client.estimate_cost("get-vessels-location-bulk", len(identifiers))
            result = fmt.format_credit_estimate(f"Track {len(identifiers)} vessels", cost) if SHOW_COST else ""

            response = await client.get_vessels_location_bulk(identifiers)
            result += f"**Fleet Positions** ({len(response['detail'])} vessels)\n\n"
            result += "| Vessel | Position | Speed | Destination |\n"
            result += "|--------|----------|-------|-------------|\n"

            for vessel in response["detail"]:
                result += f"| {vessel.get('name', 'Unknown')} | {vessel.get('latitude', 0):.2f}°N, {vessel.get('longitude', 0):.2f}°E | {vessel.get('speed', 0)} kts | {vessel.get('destination') or 'N/A'} |\n"

            result += fmt.format_credits_used(response.get("credits_used", cost), response.get("credits_remaining"))
            return [TextContent(type="text", text=result)]

        elif name == "get_vessel_history":
            identifier = arguments["identifier"]
            start_date = arguments["start_date"]
            end_date = arguments["end_date"]

            # Calculate days
            start = datetime.fromisoformat(start_date)
            end = datetime.fromisoformat(end_date)
            days = (end - start).days
            cost = client.estimate_cost("get-vessel-historical-data", days)

            result = fmt.format_credit_estimate(f"Historical data ({days} days)", cost) if SHOW_COST else ""

            response = await client.get_vessel_historical_data(identifier, start_date, end_date)
            result += fmt.format_historical_positions(response["detail"])
            result += fmt.format_credits_used(response.get("credits_used", cost), response.get("credits_remaining"))

            return [TextContent(type="text", text=result)]

        elif name == "search_vessels_by_area":
            lat1, lon1, lat2, lon2 = arguments["lat1"], arguments["lon1"], arguments["lat2"], arguments["lon2"]
            vessel_type = arguments.get("vessel_type")
            cost = client.estimate_cost("get-vessels-by-area")

            result = fmt.format_credit_estimate("Area search", cost) if SHOW_COST else ""

            response = await client.get_vessels_by_area(lat1, lon1, lat2, lon2, vessel_type)
            vessels = response["detail"]

            result += f"**Vessels in Area** ({len(vessels)} found)\n\n"
            if vessel_type:
                result += f"*Filtered by type: {vessel_type}*\n\n"

            result += "| Vessel | IMO | Position | Speed | Destination |\n"
            result += "|--------|-----|----------|-------|-------------|\n"

            for vessel in vessels[:50]:
                result += f"| {vessel.get('name', 'Unknown')} | {vessel.get('imo', 'N/A')} | {vessel.get('latitude', 0):.2f}°N, {vessel.get('longitude', 0):.2f}°E | {vessel.get('speed', 0)} kts | {vessel.get('destination') or 'N/A'} |\n"

            if len(vessels) > 50:
                result += f"\n*...and {len(vessels) - 50} more vessels*"

            result += fmt.format_credits_used(response.get("credits_used", cost), response.get("credits_remaining"))
            return [TextContent(type="text", text=result)]

        elif name == "get_vessel_details":
            imo = arguments["imo"]
            cost = client.estimate_cost("get-vessel-info")
            result = fmt.format_credit_estimate("Vessel details", cost) if SHOW_COST else ""

            response = await client.get_vessel_info(imo)
            result += fmt.format_vessel_details(response["detail"])
            result += fmt.format_credits_used(response.get("credits_used", cost), response.get("credits_remaining"))

            return [TextContent(type="text", text=result)]

        elif name == "get_vessel_specs":
            imo = arguments["imo"]
            cost = client.estimate_cost("get-vessel-particulars")
            result = fmt.format_credit_estimate("Vessel specs", cost) if SHOW_COST else ""

            response = await client.get_vessel_particulars(imo)
            result += fmt.format_vessel_particulars(response["detail"])
            result += fmt.format_credits_used(response.get("credits_used", cost), response.get("credits_remaining"))

            return [TextContent(type="text", text=result)]

        elif name == "get_vessel_engine":
            imo = arguments["imo"]
            cost = client.estimate_cost("get-engine-data")
            result = fmt.format_credit_estimate("Engine data", cost) if SHOW_COST else ""

            response = await client.get_engine_data(imo)
            result += fmt.format_engine_data(response["detail"])
            result += fmt.format_credits_used(response.get("credits_used", cost), response.get("credits_remaining"))

            return [TextContent(type="text", text=result)]

        elif name == "get_vessel_management":
            imo = arguments["imo"]
            cost = client.estimate_cost("get-management-data")
            result = fmt.format_credit_estimate("Management data", cost) if SHOW_COST else ""

            response = await client.get_management_data(imo)
            result += fmt.format_management_data(response["detail"])
            result += fmt.format_credits_used(response.get("credits_used", cost), response.get("credits_remaining"))

            return [TextContent(type="text", text=result)]

        elif name == "get_port_calls":
            identifier = arguments["identifier"]
            cost = client.estimate_cost("get-port-calls")
            result = fmt.format_credit_estimate("Port calls", cost) if SHOW_COST else ""

            response = await client.get_port_calls(identifier)
            result += fmt.format_port_calls(response["detail"])
            result += fmt.format_credits_used(response.get("credits_used", cost), response.get("credits_remaining"))

            return [TextContent(type="text", text=result)]

        elif name == "get_port_traffic":
            port_code = arguments["port_code"]
            cost = client.estimate_cost("get-port-traffic")
            result = fmt.format_credit_estimate("Port traffic", cost) if SHOW_COST else ""

            response = await client.get_port_traffic(port_code)
            result += fmt.format_port_traffic(response["detail"])
            result += fmt.format_credits_used(response.get("credits_used", cost), response.get("credits_remaining"))

            return [TextContent(type="text", text=result)]

        elif name == "get_psc_inspections":
            imo = arguments["imo"]
            cost = client.estimate_cost("get-psc-inspections")
            result = fmt.format_credit_estimate("PSC inspections", cost) if SHOW_COST else ""

            response = await client.get_psc_inspections(imo)
            result += fmt.format_psc_inspections(response["detail"])
            result += fmt.format_credits_used(response.get("credits_used", cost), response.get("credits_remaining"))

            return [TextContent(type="text", text=result)]

        elif name == "get_vessel_weather":
            latitude = arguments["latitude"]
            longitude = arguments["longitude"]
            cost = client.estimate_cost("get-weather")
            result = fmt.format_credit_estimate("Weather data", cost) if SHOW_COST else ""

            response = await client.get_weather(latitude, longitude)
            result += fmt.format_weather(response["detail"])
            result += fmt.format_credits_used(response.get("credits_used", cost), response.get("credits_remaining"))

            return [TextContent(type="text", text=result)]

        # === COMPOUND TOOLS ===
        elif name == "vessel_intelligence_report":
            imo = arguments["imo"]
            total_cost = sum([
                CREDIT_COSTS["get-vessel-location"],
                CREDIT_COSTS["get-vessel-info"],
                CREDIT_COSTS["get-vessel-particulars"],
                CREDIT_COSTS["get-engine-data"],
                CREDIT_COSTS["get-management-data"],
                CREDIT_COSTS["get-port-calls"],
                CREDIT_COSTS["get-psc-inspections"],
            ])

            result = fmt.format_credit_estimate("Vessel Intelligence Report", total_cost) if SHOW_COST else ""

            # Fetch all data in parallel
            location, details, specs, engine, management, port_calls, psc = await asyncio.gather(
                client.get_vessel_location(imo),
                client.get_vessel_info(imo),
                client.get_vessel_particulars(imo),
                client.get_engine_data(imo),
                client.get_management_data(imo),
                client.get_port_calls(imo),
                client.get_psc_inspections(imo),
            )

            result += "# VESSEL INTELLIGENCE REPORT\n\n"
            result += f"## {details['detail'].get('name', 'Unknown')} (IMO: {imo})\n\n"

            result += "### Current Position\n"
            result += fmt.format_vessel_location(location["detail"])
            result += "\n\n"

            result += "### Vessel Profile\n"
            result += fmt.format_vessel_details(details["detail"])
            result += "\n\n"

            result += "### Specifications\n"
            result += fmt.format_vessel_particulars(specs["detail"])
            result += "\n\n"

            result += "### Engine\n"
            result += fmt.format_engine_data(engine["detail"])
            result += "\n\n"

            result += "### Management\n"
            result += fmt.format_management_data(management["detail"])
            result += "\n\n"

            result += "### Port Call History\n"
            result += fmt.format_port_calls(port_calls["detail"])
            result += "\n\n"

            result += "### PSC Inspections\n"
            result += fmt.format_psc_inspections(psc["detail"])

            result += f"\n\n---\n*7 API calls | {total_cost} credits used*"

            return [TextContent(type="text", text=result)]

        elif name == "fleet_dashboard":
            identifiers = arguments["identifiers"]
            total_cost = (
                CREDIT_COSTS["get-vessels-location-bulk"] * len(identifiers) +
                CREDIT_COSTS["get-vessel-info"] * len(identifiers)
            )

            result = fmt.format_credit_estimate(f"Fleet Dashboard ({len(identifiers)} vessels)", total_cost) if SHOW_COST else ""

            # Get positions
            positions = await client.get_vessels_location_bulk(identifiers)

            # Get details for each
            detail_tasks = [client.get_vessel_info(v.get("imo", "")) for v in positions["detail"]]
            details_results = await asyncio.gather(*detail_tasks, return_exceptions=True)

            result += "# FLEET DASHBOARD\n\n"
            result += f"**{len(positions['detail'])} vessels tracked**\n\n"

            result += "| Vessel | Type | Position | Speed | Destination | ETA |\n"
            result += "|--------|------|----------|-------|-------------|-----|\n"

            for i, pos in enumerate(positions["detail"]):
                det = details_results[i] if not isinstance(details_results[i], Exception) else {}
                det_detail = det.get("detail", {}) if isinstance(det, dict) else {}
                result += f"| {pos.get('name', 'Unknown')} | {det_detail.get('type', 'Unknown')} | {pos.get('latitude', 0):.2f}°N, {pos.get('longitude', 0):.2f}°E | {pos.get('speed', 0)} kts | {pos.get('destination') or 'N/A'} | {pos.get('eta') or 'N/A'} |\n"

            result += f"\n---\n*{1 + len(identifiers)} API calls | ~{total_cost} credits used*"

            return [TextContent(type="text", text=result)]

        elif name == "voyage_analysis":
            identifier = arguments["identifier"]

            end_date = datetime.now().strftime("%Y-%m-%d")
            start_date = (datetime.now() - timedelta(days=7)).strftime("%Y-%m-%d")

            total_cost = (
                CREDIT_COSTS["get-vessel-location"] +
                CREDIT_COSTS["get-vessel-historical-data"] * 7 +
                CREDIT_COSTS["get-port-calls"] +
                CREDIT_COSTS["get-weather"]
            )

            result = fmt.format_credit_estimate("Voyage Analysis", total_cost) if SHOW_COST else ""

            location, history, port_calls = await asyncio.gather(
                client.get_vessel_location(identifier),
                client.get_vessel_historical_data(identifier, start_date, end_date),
                client.get_port_calls(identifier),
            )

            weather = await client.get_weather(
                location["detail"].get("latitude", 0),
                location["detail"].get("longitude", 0)
            )

            result += "# VOYAGE ANALYSIS\n\n"
            result += f"## {location['detail'].get('name', 'Unknown')}\n\n"

            result += "### Current Status\n"
            result += fmt.format_vessel_location(location["detail"])
            result += "\n\n"

            result += "### Weather Conditions\n"
            result += fmt.format_weather(weather["detail"])
            result += "\n\n"

            result += "### Recent Movement (7 days)\n"
            result += fmt.format_historical_positions(history["detail"])
            result += "\n\n"

            result += "### Recent Port Calls\n"
            result += fmt.format_port_calls(port_calls["detail"][:5])

            result += f"\n\n---\n*4 API calls | ~{total_cost} credits used*"

            return [TextContent(type="text", text=result)]

        elif name == "risk_assessment":
            imo = arguments["imo"]

            total_cost = (
                CREDIT_COSTS["get-psc-inspections"] +
                CREDIT_COSTS["get-management-data"] +
                CREDIT_COSTS["get-vessel-info"] +
                CREDIT_COSTS["get-port-calls"]
            )

            result = fmt.format_credit_estimate("Risk Assessment", total_cost) if SHOW_COST else ""

            psc, management, details, port_calls = await asyncio.gather(
                client.get_psc_inspections(imo),
                client.get_management_data(imo),
                client.get_vessel_info(imo),
                client.get_port_calls(imo),
            )

            result += "# RISK ASSESSMENT\n\n"
            result += f"## {details['detail'].get('name', 'Unknown')} (IMO: {imo})\n\n"

            # Calculate risk score
            psc_list = psc["detail"]
            detentions = sum(1 for i in psc_list if i.get("detained"))
            total_deficiencies = sum(i.get("deficiencies", 0) for i in psc_list)
            vessel_age = datetime.now().year - details["detail"].get("built", datetime.now().year)

            risk_score = 0
            risk_factors = []

            if detentions > 0:
                risk_score += detentions * 25
                risk_factors.append(f"{detentions} detention(s) in PSC history")
            if total_deficiencies > 10:
                risk_score += 15
                risk_factors.append(f"High deficiency count ({total_deficiencies})")
            if vessel_age > 20:
                risk_score += 10
                risk_factors.append(f"Vessel age: {vessel_age} years")

            risk_level = "HIGH" if risk_score >= 50 else "MODERATE" if risk_score >= 25 else "LOW"

            result += f"### Risk Score: {risk_score}/100 ({risk_level})\n\n"

            if risk_factors:
                result += "**Risk Factors:**\n"
                for f in risk_factors:
                    result += f"- {f}\n"
                result += "\n"

            result += "### Vessel Profile\n"
            result += f"- Type: {details['detail'].get('type', 'Unknown')}\n"
            result += f"- Flag: {details['detail'].get('flag', 'Unknown')}\n"
            result += f"- Built: {details['detail'].get('built', 'Unknown')} ({vessel_age} years old)\n\n"

            result += "### Management\n"
            result += fmt.format_management_data(management["detail"])
            result += "\n\n"

            result += "### PSC Inspection History\n"
            result += fmt.format_psc_inspections(psc_list)

            result += f"\n\n---\n*4 API calls | {total_cost} credits used*"

            return [TextContent(type="text", text=result)]

        elif name == "area_intelligence":
            lat1, lon1 = arguments["lat1"], arguments["lon1"]
            lat2, lon2 = arguments["lat2"], arguments["lon2"]
            vessel_type = arguments.get("vessel_type")
            max_vessels = arguments.get("max_vessels", 10)

            # First get vessels in area
            area_search = await client.get_vessels_by_area(lat1, lon1, lat2, lon2, vessel_type)
            vessels = area_search["detail"]

            vessels_to_detail = vessels[:max_vessels]
            total_cost = CREDIT_COSTS["get-vessels-by-area"] + CREDIT_COSTS["get-vessel-info"] * len(vessels_to_detail)

            result = fmt.format_credit_estimate("Area Intelligence", total_cost) if SHOW_COST else ""

            # Get details for each
            detail_tasks = [client.get_vessel_info(v.get("imo", "")) for v in vessels_to_detail]
            details_results = await asyncio.gather(*detail_tasks, return_exceptions=True)

            result += "# AREA INTELLIGENCE\n\n"
            result += f"**Region:** {lat1}°N, {lon1}°E to {lat2}°N, {lon2}°E\n"
            result += f"**Total vessels found:** {len(vessels)}\n"
            if vessel_type:
                result += f"**Filtered by:** {vessel_type}\n"
            result += "\n"

            result += "| Vessel | IMO | Type | Flag | Position | Speed | Destination |\n"
            result += "|--------|-----|------|------|----------|-------|-------------|\n"

            type_count: dict[str, int] = {}
            for i, pos in enumerate(vessels_to_detail):
                det = details_results[i] if not isinstance(details_results[i], Exception) else {}
                det_detail = det.get("detail", {}) if isinstance(det, dict) else {}
                vtype = det_detail.get("type", "Unknown")
                type_count[vtype] = type_count.get(vtype, 0) + 1
                result += f"| {pos.get('name', 'Unknown')} | {pos.get('imo', 'N/A')} | {vtype} | {det_detail.get('flag', 'Unknown')} | {pos.get('latitude', 0):.2f}°N, {pos.get('longitude', 0):.2f}°E | {pos.get('speed', 0)} kts | {pos.get('destination') or 'N/A'} |\n"

            if len(vessels) > max_vessels:
                result += f"\n*...and {len(vessels) - max_vessels} more vessels (increase max_vessels to see more)*\n"

            if type_count:
                result += "\n## Vessel Type Summary\n"
                for vtype, count in type_count.items():
                    result += f"- {vtype}: {count}\n"

            result += f"\n---\n*{1 + len(vessels_to_detail)} API calls | ~{total_cost} credits used*"

            return [TextContent(type="text", text=result)]

        else:
            return [TextContent(type="text", text=f"Unknown tool: {name}")]

    except Exception as e:
        return [TextContent(type="text", text=f"Error: {str(e)}")]


# ============================================
# RESOURCES
# ============================================

@server.list_resources()
async def list_resources() -> list[Resource]:
    """List available resources"""
    return [
        Resource(
            uri="datadocked://credits/balance",
            name="Credit Balance",
            description="Current DataDocked API credit balance",
            mimeType="text/plain",
        ),
    ]


@server.read_resource()
async def read_resource(uri: str) -> str:
    """Read a resource"""
    if uri == "datadocked://credits/balance":
        client = get_client()
        try:
            balance = await client.get_credit_balance()
            return f"DataDocked Credit Balance\n\nRemaining: {balance['detail'].get('credits_remaining', 'Unknown')} credits\nUsed Today: {balance['detail'].get('credits_used_today', 'Unknown')}\nPlan: {balance['detail'].get('plan', 'Unknown')}"
        except Exception as e:
            return f"Error fetching balance: {str(e)}"

    raise ValueError(f"Unknown resource: {uri}")


# ============================================
# MAIN
# ============================================

def main():
    """Run the MCP server"""
    import sys

    if not API_KEY:
        print("Error: DATADOCKED_API_KEY environment variable is required.", file=sys.stderr)
        print("Get your API key at https://datadocked.com", file=sys.stderr)
        sys.exit(1)

    async def run():
        async with stdio_server() as (read_stream, write_stream):
            await server.run(read_stream, write_stream, server.create_initialization_options())

    asyncio.run(run())


if __name__ == "__main__":
    main()
