#!/usr/bin/env python3
"""Stable launcher for the AbletonMCP-AI FastMCP server."""

from __future__ import annotations

import argparse
import os
import sys
from pathlib import Path


def _resolve_code_root() -> Path:
    wrapper_dir = Path(__file__).resolve().parent
    candidates = []

    for base in (wrapper_dir, wrapper_dir.parent):
        candidates.extend(
            [
                base / "AbletonMCP_AI" / "AbletonMCP_AI",
                base / "AbletonMCP_AI",
                base,
            ]
        )

    seen = set()
    for code_root in candidates:
        key = str(code_root).lower()
        if key in seen:
            continue
        seen.add(key)
        if (code_root / "MCP_Server" / "server.py").exists():
            return code_root

    raise FileNotFoundError("Could not locate MCP_Server/server.py from wrapper")


def main() -> int:
    parser = argparse.ArgumentParser(description="Launch AbletonMCP-AI")
    parser.add_argument("--transport", default="stdio", choices=["stdio", "sse"])
    args = parser.parse_args()

    code_root = _resolve_code_root()
    server_dir = code_root / "MCP_Server"

    os.environ.setdefault("PYTHONUNBUFFERED", "1")
    os.environ.setdefault("PYTHONIOENCODING", "utf-8")
    os.environ.setdefault("ABLETON_MCP_LAZY_STARTUP", "1")
    existing_pythonpath = os.environ.get("PYTHONPATH", "")
    pythonpath_parts = [part for part in [str(code_root), existing_pythonpath] if part]
    os.environ["PYTHONPATH"] = os.pathsep.join(pythonpath_parts)

    for path in (str(server_dir), str(code_root)):
        if path not in sys.path:
            sys.path.insert(0, path)

    from MCP_Server.server import mcp

    mcp.run(transport=args.transport)
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
