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

Vanilla Flow:
1. Download and run with zero arguments.
2. Until configured, the Thin Shell waits quietly in standby (no external network sync)
   and listens on http://127.0.0.1:19845.
3. When any user logs into the InterLoop Web GUI on this device, the Web Agent
   automatically detects the local Thin Shell and provisions it with the user's
   UID, JWT token, and remote backend API endpoint.
4. Continues running in the background even after the browser is closed or logged out,
   unless the user explicitly pauses or stops tracking.
"""

import argparse
import hashlib
from http.server import BaseHTTPRequestHandler, HTTPServer
import json
import os
import platform
import subprocess
import sys
import threading
import time
import urllib.error
import urllib.parse
import urllib.request

DEFAULT_INTERVAL = 20  # seconds between syncs
LOCAL_PORT = 19845
DEFAULT_CONFIG_PATH = os.path.expanduser("~/.interloop/interloop-shell.json")

state_lock = threading.Lock()
wake_event = threading.Event()

shell_state = {
    "config_path": DEFAULT_CONFIG_PATH,
    "server_url": "",
    "sync_endpoint": "/api/interloop/sync",
    "token": "",
    "uid": "",
    "nickname": "",
    "tracking_enabled": True,
    "should_exit": False,
    "last_sync": "",
    "last_lat": 0.0,
    "last_lng": 0.0,
    "sync_count": 0,
}


def load_config(path):
    if os.path.exists(path):
        try:
            with open(path, "r") as f:
                data = json.load(f)
            with state_lock:
                if data.get("server_url"):
                    shell_state["server_url"] = data["server_url"].rstrip("/")
                if data.get("sync_endpoint"):
                    shell_state["sync_endpoint"] = data["sync_endpoint"]
                if data.get("token"):
                    shell_state["token"] = data["token"]
                if data.get("uid"):
                    shell_state["uid"] = data["uid"]
                if data.get("nickname"):
                    shell_state["nickname"] = data["nickname"]
                if "tracking_enabled" in data:
                    shell_state["tracking_enabled"] = bool(data["tracking_enabled"])
        except Exception as e:
            print(f"[Warning] Failed to read {path}: {e}")


def save_config():
    with state_lock:
        path = shell_state["config_path"]
        payload = {
            "server_url": shell_state["server_url"],
            "sync_endpoint": shell_state["sync_endpoint"],
            "token": shell_state["token"],
            "uid": shell_state["uid"],
            "nickname": shell_state["nickname"],
            "tracking_enabled": shell_state["tracking_enabled"],
        }
    try:
        parent = os.path.dirname(os.path.abspath(path))
        if parent:
            os.makedirs(parent, exist_ok=True)
        with open(path, "w") as f:
            json.dump(payload, f, indent=2)
    except Exception as e:
        print(f"[Warning] Failed to save config to {path}: {e}")


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
    try:
        req = urllib.request.Request("http://ip-api.com/json/?fields=lat,lon,status", headers={"User-Agent": "InterLoop-ThinShell/1.2"})
        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

    return 37.7749, -122.4194, "default"


def get_battery_level():
    """Attempts to read real battery percentage on macOS and Linux."""
    sys_name = platform.system().lower()
    if sys_name == "darwin":
        try:
            res = subprocess.run(["pmset", "-g", "batt"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, timeout=2)
            if res.returncode == 0:
                import re
                m = re.search(r"(\d+)%", res.stdout)
                if m:
                    return max(1, min(100, int(m.group(1))))
        except Exception:
            pass
    elif sys_name == "linux":
        for bat in ["BAT0", "BAT1", "battery"]:
            cap_path = f"/sys/class/power_supply/{bat}/capacity"
            if os.path.exists(cap_path):
                try:
                    with open(cap_path, "r") as f:
                        return max(1, min(100, int(f.read().strip())))
                except Exception:
                    pass
    return 98


def get_device_info():
    """Generates unique device identifiers for multi-device sync management."""
    node = platform.node() or "unknown"
    sys_name = platform.system()
    dev_hash = hashlib.md5(f"{node}_{sys_name}".encode("utf-8")).hexdigest()[:8]
    dev_id = f"mac_{dev_hash}" if sys_name.lower() == "darwin" else f"pc_{dev_hash}"
    dev_type = "laptop" if sys_name.lower() in ["darwin", "windows"] else "desktop"
    label_os = "macOS" if sys_name.lower() == "darwin" else sys_name
    dev_name = f"{node} ({label_os})"
    return dev_id, dev_name, dev_type


def build_status_dict():
    dev_id, dev_name, dev_type = get_device_info()
    with state_lock:
        configured = bool(shell_state["server_url"] and shell_state["token"])
        return {
            "running": True,
            "configured": configured,
            "trackingEnabled": shell_state["tracking_enabled"],
            "serverUrl": shell_state["server_url"],
            "syncEndpoint": shell_state["sync_endpoint"],
            "uid": shell_state["uid"],
            "nickname": shell_state["nickname"],
            "deviceId": dev_id,
            "deviceName": dev_name,
            "deviceType": dev_type,
            "batteryLevel": get_battery_level(),
            "lastSync": shell_state["last_sync"],
            "lastLat": shell_state["last_lat"],
            "lastLng": shell_state["last_lng"],
            "syncCount": shell_state["sync_count"],
        }


class LocalBridgeHandler(BaseHTTPRequestHandler):
    def log_message(self, format, *args):
        pass  # Suppress noisy HTTP access logs

    def _send_cors_headers(self):
        self.send_header("Access-Control-Allow-Origin", "*")
        self.send_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
        self.send_header("Access-Control-Allow-Headers", "Content-Type, Authorization")
        self.send_header("Access-Control-Allow-Private-Network", "true")

    def _send_json(self, status_code, payload):
        body = json.dumps(payload).encode("utf-8")
        self.send_response(status_code)
        self.send_header("Content-Type", "application/json")
        self.send_header("Content-Length", str(len(body)))
        self._send_cors_headers()
        self.end_headers()
        self.wfile.write(body)

    def do_OPTIONS(self):
        self.send_response(204)
        self._send_cors_headers()
        self.end_headers()

    def do_GET(self):
        if self.path.startswith("/status") or self.path == "/":
            self._send_json(200, build_status_dict())
        else:
            self._send_json(404, {"error": "not found"})

    def do_POST(self):
        length = int(self.headers.get("Content-Length", "0") or "0")
        raw = self.rfile.read(length).decode("utf-8") if length > 0 else "{}"
        try:
            body = json.loads(raw) if raw else {}
        except Exception:
            body = {}

        if self.path.startswith("/configure"):
            server_url = (body.get("server_url") or body.get("serverUrl") or "").strip().rstrip("/")
            sync_ep = (body.get("sync_endpoint") or body.get("syncEndpoint") or "/api/interloop/sync").strip()
            token = (body.get("token") or "").strip()
            uid = (body.get("uid") or "").strip()
            nickname = (body.get("nickname") or "").strip()

            if not server_url or not token:
                self._send_json(400, {"error": "server_url and token required"})
                return

            with state_lock:
                changed = (
                    shell_state["server_url"] != server_url
                    or shell_state["token"] != token
                    or shell_state["uid"] != uid
                )
                shell_state["server_url"] = server_url
                shell_state["sync_endpoint"] = sync_ep or "/api/interloop/sync"
                shell_state["token"] = token
                if uid:
                    shell_state["uid"] = uid
                if nickname:
                    shell_state["nickname"] = nickname
                if body.get("force_enable") or changed:
                    shell_state["tracking_enabled"] = True

            save_config()
            if changed:
                ts = time.strftime("%Y-%m-%d %H:%M:%S")
                print(f"[{ts}] 🔗 Web GUI configured Thin Shell -> User: {nickname or uid or 'Account'} @ {server_url}")
            wake_event.set()
            self._send_json(200, build_status_dict())

        elif self.path.startswith("/control"):
            action = (body.get("action") or "").strip().lower()
            ts = time.strftime("%Y-%m-%d %H:%M:%S")
            if action == "pause":
                with state_lock:
                    shell_state["tracking_enabled"] = False
                save_config()
                print(f"[{ts}] ⏸️  User explicitly paused location tracking via Web GUI.")
                wake_event.set()
                self._send_json(200, build_status_dict())
            elif action == "resume":
                with state_lock:
                    shell_state["tracking_enabled"] = True
                save_config()
                print(f"[{ts}] ▶️  User resumed location tracking via Web GUI.")
                wake_event.set()
                self._send_json(200, build_status_dict())
            elif action == "stop":
                with state_lock:
                    shell_state["tracking_enabled"] = False
                    shell_state["should_exit"] = True
                save_config()
                print(f"[{ts}] 🛑 User explicitly stopped Thin Shell daemon via Web GUI.")
                self._send_json(200, {"running": False, "trackingEnabled": False, "stopped": True})
                wake_event.set()
            else:
                self._send_json(400, {"error": "unknown action"})
        else:
            self._send_json(404, {"error": "not found"})


def start_local_bridge():
    try:
        server = HTTPServer(("127.0.0.1", LOCAL_PORT), LocalBridgeHandler)
        t = threading.Thread(target=server.serve_forever, daemon=True)
        t.start()
        return server
    except Exception as e:
        print(f"[Warning] Could not bind local bridge on 127.0.0.1:{LOCAL_PORT}: {e}")
        return None


def sync_location(server_url, sync_endpoint, token, lat, lng, is_sos=False):
    """Sends telemetry payload to InterLoop sync endpoint."""
    ep = sync_endpoint if sync_endpoint.startswith("/") else "/" + sync_endpoint
    endpoint = server_url.rstrip("/") + ep
    dev_id, dev_name, dev_type = get_device_info()
    payload = {
        "latitude": lat,
        "longitude": lng,
        "batteryLevel": get_battery_level(),
        "isSOSActive": is_sos,
        "safetyCheckStatus": "ok",
        "timestamp": int(time.time() * 1000),
        "platform": "thin_shell",
        "deviceId": dev_id,
        "deviceName": dev_name,
        "deviceType": dev_type,
    }

    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.2",
    })

    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 Vanilla Thin Shell Location Updater")
    parser.add_argument("--server", help="Optional InterLoop Server URL", default="")
    parser.add_argument("--token", help="Optional JWT User Auth Token", default="")
    parser.add_argument("--group-id", help="Optional Circle ID", default="")
    parser.add_argument("--config", help="Path to config file", default=DEFAULT_CONFIG_PATH)
    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()

    with state_lock:
        shell_state["config_path"] = args.config

    load_config(args.config)

    with state_lock:
        if args.server:
            shell_state["server_url"] = args.server.rstrip("/")
        elif os.environ.get("INTERLOOP_SERVER"):
            shell_state["server_url"] = os.environ["INTERLOOP_SERVER"].rstrip("/")
        if args.token:
            shell_state["token"] = args.token
        elif os.environ.get("INTERLOOP_TOKEN"):
            shell_state["token"] = os.environ["INTERLOOP_TOKEN"]

    if args.server or args.token:
        save_config()

    start_local_bridge()

    dev_id, dev_name, _ = get_device_info()
    print(f"🚀 InterLoop Vanilla Thin Shell started ({dev_name})")
    print(f"   Local Web GUI Bridge: http://127.0.0.1:{LOCAL_PORT}")
    with state_lock:
        if shell_state["server_url"] and shell_state["token"]:
            print(f"   Configured Endpoint : {shell_state['server_url']}{shell_state['sync_endpoint']}")
        else:
            print("   ⏳ Status: STANDBY — Waiting for user login on Web GUI to auto-configure...")
    print("--------------------------------------------------")

    try:
        while True:
            wake_event.clear()
            with state_lock:
                should_exit = shell_state["should_exit"]
                server = shell_state["server_url"]
                sync_ep = shell_state["sync_endpoint"]
                token = shell_state["token"]
                tracking_enabled = shell_state["tracking_enabled"]

            if should_exit:
                print("👋 Thin Shell exiting as requested by user.")
                break

            # If not configured yet, or explicitly paused by user, do not send any telemetry
            if not server or not token or not tracking_enabled:
                wake_event.wait(timeout=args.interval)
                continue

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

            if code == 200:
                with state_lock:
                    shell_state["last_sync"] = ts
                    shell_state["last_lat"] = lat
                    shell_state["last_lng"] = lng
                    shell_state["sync_count"] += 1

                tracking_status = resp.get("trackingStatus", "active")
                if tracking_status == "paused":
                    print(f"[{ts}] ⏸️  Server instructed PAUSE. Sleeping 60s...")
                    wake_event.wait(timeout=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
            wake_event.wait(timeout=args.interval)
    except KeyboardInterrupt:
        print("\n👋 Thin Shell stopped.")


if __name__ == "__main__":
    main()
