"""
One-time setup for MineConnect cloudflared tunnels.

Creates two named tunnels, routes DNS to ideadev.me subdomains,
and patches the YAML config files with the real tunnel IDs.

Usage:
    mineconnect-setup  # After pip install
    OR
    python -m mineconnect.tunnel_setup
"""

import subprocess
import os
import sys
import json

DOMAIN = "ideadev.me"


def _run(cmd, check=False):
    print(f"  $ {' '.join(cmd)}")
    result = subprocess.run(cmd, capture_output=True, text=True)
    out = (result.stdout + result.stderr).strip()
    if out:
        for line in out.splitlines():
            print(f"    {line}")
    if check and result.returncode != 0:
        sys.exit(f"Command failed (exit {result.returncode})")
    return result


def _patch_config(config_dir, filename, tunnel_id):
    path = os.path.join(config_dir, filename)
    if not os.path.exists(path):
        return
    with open(path, "r", encoding="utf-8") as fh:
        text = fh.read()
    text = text.replace("TUNNEL_ID_HERE", tunnel_id)
    with open(path, "w", encoding="utf-8") as fh:
        fh.write(text)
    print(f"  -> Updated {filename}")


def main():
    print("=" * 56)
    print("  MineConnect  —  Tunnel Setup")
    print("=" * 56)

    # Get config directory (parent of package)
    package_dir = os.path.dirname(os.path.abspath(__file__))
    config_dir = os.path.dirname(package_dir)

    # 1 — Login
    print("\n[1/5] Cloudflare authentication")
    print("  A browser window will open — please log in.")
    _run(["cloudflared", "tunnel", "login"])

    # 2 — Create tunnels
    for name in ("mineconnect-java", "mineconnect-bedrock"):
        print(f"\n[2/5] Creating tunnel: {name}")
        _run(["cloudflared", "tunnel", "create", name])

    # 3 — DNS routing
    print(f"\n[3/5] Routing java.{DOMAIN}")
    _run([
        "cloudflared", "tunnel", "route", "dns",
        "mineconnect-java", f"java.{DOMAIN}",
    ])

    print(f"\n[4/5] Routing bedrock.{DOMAIN}")
    _run([
        "cloudflared", "tunnel", "route", "dns",
        "mineconnect-bedrock", f"bedrock.{DOMAIN}",
    ])

    # 4 — Patch config files with real tunnel IDs
    print("\n[5/5] Updating config files")
    result = _run(["cloudflared", "tunnel", "list", "-o", "json"])
    if result.stdout:
        try:
            tunnels = json.loads(result.stdout)
            for t in tunnels:
                name = t.get("name", "")
                tid = t.get("id", "")
                if name == "mineconnect-java":
                    _patch_config(config_dir, "tunnel_java.yml", tid)
                elif name == "mineconnect-bedrock":
                    _patch_config(config_dir, "tunnel_bedrock.yml", tid)
        except json.JSONDecodeError:
            print("  !! Could not parse tunnel list — edit configs manually.")

    print("\n" + "=" * 56)
    print("  Setup complete!")
    print("=" * 56)


if __name__ == "__main__":
    main()
