"""
meshpop_startup.py — zero-step MCP auto-configuration + PATH fix.

Installed to site-packages via pip. Called once (on first Python start after
install) to:
  1. Register all MeshPOP MCP servers with every detected AI tool (#3)
  2. Add pip scripts dir to ~/.zshrc / ~/.bashrc so 'mpop' works in terminal (#2)

This module is triggered by meshpop_startup.pth in site-packages:
    import meshpop_startup
"""
import os as _os


def _fix_terminal_path():
    """#2: Add pip scripts dir to shell rc files if 'mpop' isn't reachable.

    Covers all common setups:
      - macOS pip:    ~/Library/Python/3.x/bin/
      - Linux pip:    ~/.local/bin/
      - conda:        ~/miniforge3/bin/ (already in PATH — skipped)
      - pyenv:        ~/.pyenv/versions/.../bin/ (already in PATH — skipped)

    Uses a separate marker so it only rewrites rc files once.
    """
    import sysconfig as _sc

    HOME = _os.path.expanduser("~")
    PATH_MARKER = _os.path.join(HOME, ".mpop", ".path-configured")
    if _os.path.exists(PATH_MARKER):
        return

    scripts_dir = _sc.get_path("scripts")
    if not scripts_dir or not _os.path.isdir(scripts_dir):
        return

    # Already in current PATH? (e.g. conda/pyenv environments)
    current_path = _os.environ.get("PATH", "")
    if scripts_dir in current_path.split(":"):
        # Mark done — no rc change needed
        try:
            _os.makedirs(_os.path.dirname(PATH_MARKER), exist_ok=True)
            open(PATH_MARKER, "w").close()
        except Exception:
            pass
        return

    # Build the line to add
    export_line = f'export PATH="{scripts_dir}:$PATH"  # meshpop'

    # Candidate rc files (write to whichever exists, skip if neither)
    rc_candidates = [
        _os.path.join(HOME, ".zshrc"),
        _os.path.join(HOME, ".bashrc"),
        _os.path.join(HOME, ".bash_profile"),
    ]

    wrote_any = False
    for rc in rc_candidates:
        try:
            # Check if already present
            if _os.path.exists(rc):
                with open(rc) as _f:
                    if scripts_dir in _f.read():
                        wrote_any = True
                        continue  # already there

            # Append only if the file exists (don't create rc files)
            if _os.path.exists(rc):
                with open(rc, "a") as _f:
                    _f.write(f"\n{export_line}\n")
                wrote_any = True
        except Exception:
            pass

    # Mark done regardless (don't retry on every Python startup)
    try:
        _os.makedirs(_os.path.dirname(PATH_MARKER), exist_ok=True)
        open(PATH_MARKER, "w").close()
    except Exception:
        pass


def _run():
    HOME   = _os.path.expanduser("~")
    MARKER = _os.path.join(HOME, ".mpop", ".mcp-configured")

    # Always try to fix PATH (separate marker) — cheap check
    try:
        _fix_terminal_path()
    except Exception:
        pass  # never crash Python startup

    # Auto-restart local agent when meshpop version changes (server-side self-heal)
    try:
        _agent_service = "/etc/systemd/system/mpop-agent.service"
        _agent_dest = "/opt/server-agent/agent-reporter.py"
        if _os.path.exists(_agent_service) and _os.path.exists(_os.path.dirname(_agent_dest)):
            import importlib.metadata as _im
            _cur_ver = _im.version("meshpop")
            _agent_ver_marker = _os.path.join(HOME, ".mpop", ".agent_ver")
            _prev_ver = open(_agent_ver_marker).read().strip() if _os.path.exists(_agent_ver_marker) else ""
            if _prev_ver != _cur_ver:
                import agent_reporter as _ar
                import shutil as _sh
                _sh.copy(_ar.__file__, _agent_dest)
                import subprocess as _sp
                _sp.run(["systemctl", "restart", "mpop-agent"], capture_output=True, timeout=10)
                _os.makedirs(_os.path.dirname(_agent_ver_marker), exist_ok=True)
                open(_agent_ver_marker, "w").write(_cur_ver)
    except Exception:
        pass  # never crash Python startup

    if _os.path.exists(MARKER):
        return  # MCP already configured — nothing more to do
    try:
        # mpop must be importable (it's installed alongside us)
        import mpop as _mpop
        _mpop._auto_configure_mcp_silent()
    except Exception:
        pass  # never crash Python startup


_run()
