"""Idempotent Tailscale Serve wiring for tailnet-remote seats (V3-PLAN §1.7).

The server binds loopback only; remote reach is *exclusively* Tailscale Serve —
TLS terminated by tailscaled, access gated by tailnet membership, and Serve
(unlike Funnel) is never public. Re-applying the same proxy config is a no-op
for tailscale, so calling this on every server start (the KeepAlive restart
path) is the idempotent wiring the plan asks for. Everything here is
best-effort by design: a box without tailscale (or with Serve declined) still
serves local seats on 127.0.0.1.
"""
import shutil
import subprocess

# The GUI app on macOS ships the CLI inside the bundle; PATH usually lacks it.
_MACOS_APP_CLI = "/Applications/Tailscale.app/Contents/MacOS/Tailscale"


def _cli():
    exe = shutil.which("tailscale")
    if exe:
        return exe
    import os
    return _MACOS_APP_CLI if os.path.exists(_MACOS_APP_CLI) else None


def ensure_serve(port, config=None) -> str:
    """Point ``https://<host>.<tailnet>.ts.net`` at the local server. Returns a
    one-line status for the log; never raises."""
    vm = ((config or {}).get("vault_mcp")) or {}
    if vm.get("tailscale_serve") is False:
        return "tailscale serve: disabled (vault_mcp.tailscale_serve)"
    exe = _cli()
    if not exe:
        return "tailscale serve: skipped (tailscale not installed — local seats only)"
    try:
        r = subprocess.run([exe, "serve", "--bg", f"http://127.0.0.1:{port}"],
                           capture_output=True, text=True, timeout=15)
    except (OSError, subprocess.TimeoutExpired) as e:
        return f"tailscale serve: failed ({e})"
    if r.returncode != 0:
        return ("tailscale serve: failed — " + (r.stderr or r.stdout).strip().replace("\n", " ")
                + " (remote seats unavailable; local seats unaffected)")
    return "tailscale serve: proxying the tailnet HTTPS name to 127.0.0.1:%d" % port
