#!/usr/bin/env python3
# scripts/mesh_handshake.py
import subprocess
import sys
import webbrowser


def check_ip(ip):
    try:
        # Simple ping check for reachability
        subprocess.run(
            ["ping", "-c", "1", "-W", "1", ip],
            stdout=subprocess.DEVNULL,
            stderr=subprocess.DEVNULL,
            check=True,
        )
        return True
    except subprocess.CalledProcessError:
        return False


def main():
    print("Initializing Tailscale Mesh Handshake for Unit 02...")

    # Discovery Phase
    target_user = "howsa"
    primary_ip = "192.168.x.x"
    usb_ip = "192.168.55.1"
    target_ip = None

    print(f"Searching for remote node ({primary_ip})...")
    if check_ip(primary_ip):
        target_ip = primary_ip
        print(f"Connected to node via Network ({primary_ip}).")
    else:
        print(f"Network node not found. Checking USB fallback ({usb_ip})...")
        if check_ip(usb_ip):
            target_ip = usb_ip
            print(f"Connected to node via USB Bridge ({usb_ip}).")
        else:
            print("Error: Could not reach node via Network or USB Bridge.")
            sys.exit(1)

    print("\nOpening Tailscale Admin Console to generate Auth Key...")
    webbrowser.open("https://login.tailscale.com/admin/settings/keys")

    auth_key = input("\nEnter your Tailscale Auth Key (must start with 'tskey-auth-'): ").strip()

    if not auth_key.startswith("tskey-auth-"):
        print("Error: Invalid Auth Key format.")
        sys.exit(1)

    hostname = "engram-node-01"
    print(f"Executing remote handshake on {target_ip}...")

    cmd = [
        "ssh",
        "-t",
        f"{target_user}@{target_ip}",
        f"sudo tailscale up --authkey {auth_key} --hostname {hostname}",
    ]

    try:
        subprocess.run(cmd, check=True)
        print("\nMesh handshake successful.")
    except subprocess.CalledProcessError as e:
        print(f"\nMesh handshake failed: {e}")
        sys.exit(1)


if __name__ == "__main__":
    main()
