#!/usr/bin/env python3
"""intrikata-topology-local-bridge — thin launcher.

DRY: the canonical implementation is Plush Rust `plush-tunnel` (plane A).
This script prefers the installed artifact, then falls back to a minimal
stdlib path only when the binary is missing (so agents still work pre-build).

Build / install (from plush repo):
  cd plush
  .\\deploy\\cloudflare-tunnel\\install-artifact.ps1

That copies plush-tunnel.exe next to this script when Intrikata is a sibling
of plush under Documents/.
"""
from __future__ import annotations

import os
import shutil
import subprocess
import sys
from pathlib import Path

HERE = Path(__file__).resolve().parent
CANDIDATES = [
    HERE / "plush-tunnel.exe",
    HERE / "plush-tunnel",
    HERE.parent.parent.parent / "plush" / "deploy" / "cloudflare-tunnel" / "bin" / "plush-tunnel.exe",
    HERE.parent.parent.parent / "plush" / "backend" / "target" / "release" / "plush-tunnel.exe",
    HERE.parent.parent.parent / "plush" / "backend" / "target" / "debug" / "plush-tunnel.exe",
]


def find_rust_bin() -> Path | None:
    env = os.environ.get("PLUSH_TUNNEL_BIN", "").strip()
    if env and Path(env).is_file():
        return Path(env)
    for p in CANDIDATES:
        if p.is_file():
            return p
    which = shutil.which("plush-tunnel")
    return Path(which) if which else None


def main() -> int:
    rust = find_rust_bin()
    if rust:
        # Map legacy Python flags → plush-tunnel CLI
        argv = list(sys.argv[1:])
        # Default to intrikata subcommand when no subcommand given
        if not argv or argv[0].startswith("-"):
            cmd = [str(rust), "intrikata"] + argv
        elif argv[0] in ("intrikata", "plush", "named", "run"):
            cmd = [str(rust)] + argv
        else:
            # Unknown legacy: pass through as intrikata args
            cmd = [str(rust), "intrikata"] + argv

        # Translate common legacy flags
        translated = []
        i = 0
        while i < len(cmd):
            a = cmd[i]
            if a == "--base":
                translated.extend(["--base", cmd[i + 1]])
                i += 2
            elif a == "--session":
                translated.extend(["--session", cmd[i + 1]])
                i += 2
            elif a == "--upstream-only":
                translated.append("--upstream-only")
                i += 1
            elif a == "--origin":
                translated.extend(["--origin", cmd[i + 1]])
                i += 2
            elif a == "--port":
                # legacy --port N → origin http://127.0.0.1:N
                port = cmd[i + 1]
                translated.extend(["--origin", f"http://127.0.0.1:{port}"])
                i += 2
            elif a == "--no-open":
                # rust binary does not open browser; ignore
                i += 1
            else:
                translated.append(a)
                i += 1

        print(f"plush-tunnel  {rust}", flush=True)
        return subprocess.call(translated)

    print(
        "plush-tunnel binary not found — install from plush:\n"
        "  cd Documents\\plush\n"
        "  .\\deploy\\cloudflare-tunnel\\install-artifact.ps1\n"
        "Requires Rust + MSVC (or MinGW dlltool). Falling back to stdlib bridge…",
        file=sys.stderr,
        flush=True,
    )
    # Fallback: exec legacy module next to us if present
    legacy = HERE / "_intrikata_topology_local_bridge_legacy.py"
    if legacy.is_file():
        return subprocess.call([sys.executable, str(legacy)] + sys.argv[1:])
    print(
        "No legacy fallback either. Install plush-tunnel (see plush-tunnel README).",
        file=sys.stderr,
    )
    return 2


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