#!/usr/bin/env python3
"""
InterLoop Thin Shell - Headless Background Location Updater Daemon
==================================================================
A lightweight, zero-dependency background client designed for continuous
real-time telemetry and GPS sync without requiring a web browser.

Usage:
  python3 interloop-shell.py --server https://aiproxy.interloop.live --token <JWT> --group-id <GROUP_UUID>

Or paired automatically from Web UI via JSON or scan.
"""

import argparse
import json
import os
import platform
import subprocess
import sys
import time
import urllib.error
import urllib.parse
import urllib.request

DEFAULT_INTERVAL = 20  # seconds between syncs


def get_system_location():
    """Attempts to obtain device coordinates via OS APIs or network fallback."""
    sys_name = platform.system().lower()

    # 1. macOS CoreLocation via whereami or corelocationcli if installed
    if sys_name == "darwin":
        for cmd in ["whereami", "CoreLocationCLI"]:
            try:
                res = subprocess.run([cmd, "-f", "%latitude,%longitude"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, timeout=3)
                if res.returncode == 0 and "," in res.stdout:
                    parts = res.stdout.strip().split(",")
                    return float(parts[0]), float(parts[1]), "macos-corelocation"
            except Exception:
                pass

    # 2. Linux GeoClue or termux-location if running on Android Termux
    if sys_name == "linux":
        if os.path.exists("/data/data/com.termux"):
            try:
                res = subprocess.run(["termux-location"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, timeout=4)
                if res.returncode == 0:
                    data = json.loads(res.stdout)
                    return float(data.get("latitude")), float(data.get("longitude")), "android-termux"
            except Exception:
                pass

    # 3. Network Geolocation Fallback (Fast & reliable fallback)
    try:
        req = urllib.request.Request("http://ip-api.com/json/?fields=lat,lon,status", headers={"User-Agent": "InterLoop-ThinShell/1.0"})
        with urllib.request.urlopen(req, timeout=4) as response:
            data = json.loads(response.read().decode("utf-8"))
            if data.get("status") == "success":
                return float(data.get("lat")), float(data.get("lon")), "network-ip"
    except Exception:
        pass

    # Fallback default if completely offline/unreachable
    return 37.7749, -122.4194, "default"


def sync_location(server_url, token, lat, lng, is_sos=False):
    """Sends telemetry payload to InterLoop sync endpoint."""
    endpoint = server_url.rstrip("/") + "/api/interloop/sync"
    payload = {
        "latitude": lat,
        "longitude": lng,
        "batteryLevel": 98,
        "isSOSActive": is_sos,
        "safetyCheckStatus": "ok",
        "timestamp": int(time.time() * 1000)
    }

    data = json.dumps(payload).encode("utf-8")
    req = urllib.request.Request(endpoint, data=data, method="POST", headers={
        "Content-Type": "application/json",
        "Authorization": f"Bearer {token}",
        "User-Agent": "InterLoop-ThinShell/1.0"
    })

    try:
        with urllib.request.urlopen(req, timeout=10) as resp:
            body = resp.read().decode("utf-8")
            return resp.status, json.loads(body)
    except urllib.error.HTTPError as e:
        err_body = e.read().decode("utf-8", errors="ignore")
        return e.code, {"error": err_body}
    except Exception as e:
        return 0, {"error": str(e)}


def main():
    parser = argparse.ArgumentParser(description="InterLoop Thin Shell Location Updater")
    parser.add_argument("--server", help="InterLoop Server URL (e.g. https://aiproxy.interloop.live)", default="")
    parser.add_argument("--token", help="JWT User Auth Token", default="")
    parser.add_argument("--group-id", help="Active Circle / Loop ID", default="")
    parser.add_argument("--config", help="Path to config file", default="interloop-shell.json")
    parser.add_argument("--interval", help="Sync interval in seconds", type=int, default=DEFAULT_INTERVAL)
    parser.add_argument("--daemon", help="Run continuously in background loop", action="store_true", default=True)
    args = parser.parse_args()

    # Load from config file if exists
    config = {}
    if os.path.exists(args.config):
        try:
            with open(args.config, "r") as f:
                config = json.load(f)
        except Exception as e:
            print(f"[Warning] Failed to read {args.config}: {e}")

    server = args.server or config.get("server_url") or os.environ.get("INTERLOOP_SERVER")
    token = args.token or config.get("token") or os.environ.get("INTERLOOP_TOKEN")

    if not server or not token:
        print("Error: --server and --token are required (or supply config file)")
        print("Example: python3 interloop-shell.py --server https://aiproxy.interloop.live --token <TOKEN>")
        sys.exit(1)

    print(f"🚀 InterLoop Thin Shell active")
    print(f"   Target Server: {server}")
    print(f"   Sync Interval: {args.interval}s")
    print("--------------------------------------------------")

    try:
        while True:
            lat, lng, source = get_system_location()
            code, resp = sync_location(server, token, lat, lng)
            ts = time.strftime("%Y-%m-%d %H:%M:%S")

            if code == 200:
                tracking_status = resp.get("trackingStatus", "active")
                if tracking_status == "paused":
                    print(f"[{ts}] ⏸️  Server instructed PAUSE. Sleeping 60s...")
                    time.sleep(60)
                    continue

                active_users = len(resp.get("locations", []))
                print(f"[{ts}] ✅ Synced {lat:.4f}, {lng:.4f} ({source}) -> {active_users} circle members active")
            else:
                print(f"[{ts}] ❌ Sync failed (HTTP {code}): {resp.get('error')}")

            if not args.daemon:
                break
            time.sleep(args.interval)
    except KeyboardInterrupt:
        print("\n👋 Thin Shell stopped.")


if __name__ == "__main__":
    main()
