"""Launcher generator for MCP servers — parameterized, auto-updates via uvx on every start."""

from __future__ import annotations

import stat
import textwrap
from pathlib import Path

from .config_helpers import ensure_config_dir


def build_launcher_source(
    package_name: str,
    executable_name: str,
) -> str:
    """Return the launcher script content as a string.
    
    Args:
        package_name: PyPI package name (e.g., "5mghost-rover")
        executable_name: Executable name (e.g., "reddit-mcp")
    """
    return textwrap.dedent(f'''\
        #!/usr/bin/env python3
        """{executable_name} launcher — auto-updates via uvx on every start."""
        import subprocess, sys, shutil

        PACKAGE = "{package_name}"
        EXECUTABLE = "{executable_name}"
        ARGS = sys.argv[1:] or ["serve"]

        def main():
            uvx = shutil.which("uvx")
            if uvx:
                # --from maps PyPI package name to its executable
                sys.exit(subprocess.run([uvx, "--from", PACKAGE, EXECUTABLE, *ARGS]).returncode)

            # fallback: use globally installed executable
            bin_path = shutil.which(EXECUTABLE)
            if bin_path:
                sys.exit(subprocess.run([bin_path, *ARGS]).returncode)

            sys.stderr.write(f"Error: uvx not found, {{EXECUTABLE}} not installed globally.\\n")
            sys.stderr.write(f"Install: pip install {{PACKAGE}}  OR  uv tool install {{PACKAGE}}\\n")
            sys.exit(1)

        if __name__ == "__main__":
            main()
    ''')


def write_uvx_launcher(
    *,
    package_name: str,
    executable_name: str,
    config_dir: Path,
) -> Path:
    """Write the launcher script and return its path.
    
    Args:
        package_name: PyPI package name
        executable_name: Executable name
        config_dir: Config directory (e.g., Path.home() / ".reddit-mcp")
    
    Returns:
        Path to the generated launcher script
    """
    ensure_config_dir(config_dir)
    launcher_path = config_dir / "launcher.py"
    launcher_path.write_text(build_launcher_source(package_name, executable_name), "utf-8")
    # chmod 755
    launcher_path.chmod(
        stat.S_IRWXU | stat.S_IRGRP | stat.S_IXGRP | stat.S_IROTH | stat.S_IXOTH
    )
    return launcher_path
