"""
AIdrac MCP Server - AI Out-of-Band Management
=============================================

MCP server providing remote system control tools.
"""

import asyncio
import json
from mcp.server import Server
from mcp.types import Tool, TextContent
from mcp.server.stdio import stdio_server

from .protocols.dtmf import DTMF
from .protocols.ultrasonic import Ultrasonic, UltrasonicMode
from .transports.ntfy import Ntfy
from .transports.ipoll_bridge import IPollBridge

server = Server("aidrac")


@server.list_tools()
async def list_tools() -> list[Tool]:
    return [
        Tool(
            name="aidrac_dtmf_encode",
            description="Convert text to DTMF digit sequence (phone keypad)",
            inputSchema={
                "type": "object",
                "properties": {
                    "text": {"type": "string", "description": "Text to encode"}
                },
                "required": ["text"]
            }
        ),
        Tool(
            name="aidrac_dtmf_generate",
            description="Generate DTMF tones for a digit sequence",
            inputSchema={
                "type": "object",
                "properties": {
                    "digits": {"type": "string", "description": "DTMF digits (0-9, *, #, A-D)"}
                },
                "required": ["digits"]
            }
        ),
        Tool(
            name="aidrac_ultrasonic_encode",
            description="Encode data for ultrasonic transmission",
            inputSchema={
                "type": "object",
                "properties": {
                    "data": {"type": "string", "description": "Data to encode"},
                    "mode": {
                        "type": "string",
                        "enum": ["audible", "ultrasonic", "stealth"],
                        "default": "ultrasonic"
                    }
                },
                "required": ["data"]
            }
        ),
        Tool(
            name="aidrac_ntfy_send",
            description="Send notification via ntfy.sh",
            inputSchema={
                "type": "object",
                "properties": {
                    "message": {"type": "string", "description": "Message to send"},
                    "topic": {"type": "string", "default": "aidrac", "description": "ntfy topic"},
                    "title": {"type": "string", "description": "Optional title"},
                    "priority": {
                        "type": "string",
                        "enum": ["min", "low", "default", "high", "urgent"],
                        "default": "default"
                    }
                },
                "required": ["message"]
            }
        ),
        Tool(
            name="aidrac_ipoll_send",
            description="Send command via I-Poll to another AIdrac instance",
            inputSchema={
                "type": "object",
                "properties": {
                    "to_agent": {"type": "string", "description": "Target agent ID"},
                    "command": {"type": "string", "description": "Command to send"}
                },
                "required": ["to_agent", "command"]
            }
        ),
        Tool(
            name="aidrac_status",
            description="Get AIdrac system status",
            inputSchema={"type": "object", "properties": {}}
        ),
    ]


@server.call_tool()
async def call_tool(name: str, arguments: dict) -> list[TextContent]:

    if name == "aidrac_dtmf_encode":
        text = arguments["text"]
        result = DTMF.from_text(text)
        return [TextContent(type="text", text=f"DTMF sequence: {result}")]

    elif name == "aidrac_dtmf_generate":
        digits = arguments["digits"]
        dtmf = DTMF()
        audio = dtmf.generate(digits)
        return [TextContent(type="text", text=f"Generated {len(audio)} samples for '{digits}'")]

    elif name == "aidrac_ultrasonic_encode":
        data = arguments["data"]
        mode = UltrasonicMode(arguments.get("mode", "ultrasonic"))
        ultra = Ultrasonic(mode=mode)
        audio = ultra.encode(data.encode())
        duration = ultra.estimate_duration(len(data))
        return [TextContent(type="text", text=f"Encoded {len(data)} bytes, duration: {duration:.2f}s, mode: {mode.value}")]

    elif name == "aidrac_ntfy_send":
        message = arguments["message"]
        topic = arguments.get("topic", "aidrac")
        title = arguments.get("title")
        priority = arguments.get("priority", "default")

        ntfy = Ntfy(topic=topic)
        success = ntfy.send(message, title=title, priority=priority)
        return [TextContent(type="text", text=f"Sent to ntfy/{topic}: {success}")]

    elif name == "aidrac_ipoll_send":
        to_agent = arguments["to_agent"]
        command = arguments["command"]

        bridge = IPollBridge(agent_id="aidrac_mcp")
        success = bridge.send(to_agent, command)
        return [TextContent(type="text", text=f"Sent to {to_agent} via I-Poll: {success}")]

    elif name == "aidrac_status":
        status = {
            "version": "0.1.0",
            "transports": ["dtmf", "ultrasonic", "ntfy", "ipoll"],
            "protocols": ["DTMF", "FSK/ggwave", "HTTP"],
            "status": "operational"
        }
        return [TextContent(type="text", text=json.dumps(status, indent=2))]

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


def main():
    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()
