#!/usr/bin/env bash
# SOVEREIGN_COMMISSION: 📐 [LICENSE:ARCHITECTURAL]
# MasiDyn Chromebook Edition — Crostini (penguin) + Native ChromeOS On-the-Go Installer
#
# Usage inside Chromebook Linux terminal (penguin):
#   curl -fsSL https://masidyn.com/download/chromebook/penguin.sh | bash
#   (or: curl -fsSL https://masidyn.dev/install-chromebook.sh | bash)
set -euo pipefail

ORIGIN="${MASIDYN_ORIGIN:-https://masidyn.com}"
DEV_ORIGIN="${MASIDYN_DEV_ORIGIN:-https://masidyn.dev}"
HOME_DIR="${MASIDYN_HOME:-$HOME/.masidyn}"
BIN_DIR="${MASIDYN_BIN:-$HOME/.local/bin}"
CHROMEOS_EXT_DIR="${MASIDYN_CHROMEOS_BRIDGE_DIR:-$HOME_DIR/chromeos_native_bridge}"
BRIDGE_PORT="${MASIDYN_PENGUIN_PORT:-11460}"

say() { printf '  [masidyn-chromebook] %s\n' "$*"; }
die() { printf '  [masidyn-chromebook] ERROR: %s\n' "$*" >&2; exit 1; }

PY=""
for c in python3 python; do
  if command -v "$c" >/dev/null 2>&1; then PY="$c"; break; fi
done
[ -n "$PY" ] || die "Python 3 is required inside Crostini (penguin). Run: sudo apt update && sudo apt install -y python3 curl"

mkdir -p "$HOME_DIR" "$BIN_DIR" "$CHROMEOS_EXT_DIR"

fetch() {
  if command -v curl >/dev/null 2>&1; then curl -fsSL "$1" -o "$2"
  elif command -v wget >/dev/null 2>&1; then wget -qO "$2" "$1"
  else die "curl or wget is required"; fi
}

say "Detected host: $(hostname 2>/dev/null || echo penguin) · Configuring Crostini penguin + Native ChromeOS pipes..."
say "Piped Praetor seats: masidyn,white,purple,blue,green,yellow,red,orange,pink"

# 1. Fetch MasiDyn CLI & SDK clients when reachable (graceful offline fallback included)
fetch "$ORIGIN/cli" "$HOME_DIR/masidyn_chat.py" 2>/dev/null || true
fetch "$DEV_ORIGIN/clients/masidyn_pick.py" "$HOME_DIR/masidyn_pick.py" 2>/dev/null || true
fetch "$DEV_ORIGIN/clients/masidyn_client.py" "$HOME_DIR/masidyn_client.py" 2>/dev/null || true
fetch "$DEV_ORIGIN/clients/masidyn_hardware_tier.py" "$HOME_DIR/masidyn_hardware_tier.py" 2>/dev/null || true

# 2. Write the On-the-Go Crostini <-> Native ChromeOS Bridge Daemon (binds 0.0.0.0:11460 -> penguin.linux.test:11460)
cat > "$HOME_DIR/penguin_bridge_daemon.py" <<'PYEOF'
#!/usr/bin/env python3
"""MasiDyn Crostini (penguin) <-> Native ChromeOS On-the-Go Bridge Daemon.

Exposes http://penguin.linux.test:11460 to Native ChromeOS and routes all Praetor seats
(masidyn, white, purple, blue, green, yellow, red, orange, pink) across:
  1. Local Crostini runtime (http://127.0.0.1:11435)
  2. Home LAN OMEN Max Flagship BC-01 (http://192.168.1.10:11460 / :11435)
  3. On-the-Go Sovereign Tunnel (https://masidyn.com / https://masidyn.dev)
"""
import json, os, sys, time, urllib.request
from http.server import BaseHTTPRequestHandler, HTTPServer

PORT = int(os.environ.get("MASIDYN_PENGUIN_PORT", "11460"))
SEATS = ["masidyn", "white", "purple", "blue", "green", "yellow", "red", "orange", "pink"]
UPSTREAMS = [
    ("local_prime", os.environ.get("MASIDYN_LOCAL_PRIME", "http://127.0.0.1:11435")),
    ("omen_lan_bc01", os.environ.get("MASIDYN_OMEN_LAN", "http://192.168.1.10:11460")),
    ("on_the_go_tunnel", os.environ.get("MASIDYN_TUNNEL_URL", "https://masidyn.com")),
]

def probe_upstream():
    for name, base in UPSTREAMS:
        path = "/health" if "11435" in base else "/api/health"
        try:
            req = urllib.request.Request(base.rstrip("/") + path, headers={"User-Agent": "MasiDyn-Penguin-Bridge/1.0"})
            with urllib.request.urlopen(req, timeout=1.2) as r:
                if 200 <= r.status < 500:
                    return {"route_id": name, "base_url": base, "on_the_go": name == "on_the_go_tunnel"}
        except Exception:
            continue
    return {"route_id": "on_the_go_tunnel", "base_url": "https://masidyn.com", "on_the_go": True}

class PenguinHandler(BaseHTTPRequestHandler):
    def log_message(self, *args):
        pass
    def _cors(self):
        self.send_header("Access-Control-Allow-Origin", "*")
        self.send_header("Access-Control-Allow-Headers", "Content-Type, Authorization")
        self.send_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
    def do_OPTIONS(self):
        self.send_response(204); self._cors(); self.end_headers()
    def do_GET(self):
        route = probe_upstream()
        if self.path.startswith("/api/health") or self.path == "/health":
            body = json.dumps({"ok": True, "node": "FFG-03-penguin", "host": "penguin.linux.test", "port": PORT, "active_route": route, "piped_seats": SEATS}).encode("utf-8")
            self.send_response(200); self._cors(); self.send_header("Content-Type", "application/json"); self.end_headers(); self.wfile.write(body)
            return
        body = json.dumps({"schema": "masidyn-penguin-bridge/v1", "active_route": route, "piped_seats": SEATS, "chromeos_url": f"http://penguin.linux.test:{PORT}"}).encode("utf-8")
        self.send_response(200); self._cors(); self.send_header("Content-Type", "application/json"); self.end_headers(); self.wfile.write(body)
    def do_POST(self):
        n = int(self.headers.get("Content-Length") or 0)
        raw = self.rfile.read(n) if n > 0 else b"{}"
        route = probe_upstream()
        target = route["base_url"].rstrip("/") + "/api/chat"
        try:
            req = urllib.request.Request(target, data=raw, headers={"Content-Type": "application/json", "User-Agent": "MasiDyn-Penguin-Bridge/1.0"})
            with urllib.request.urlopen(req, timeout=90) as r:
                resp = r.read()
            self.send_response(200); self._cors(); self.send_header("Content-Type", "application/json"); self.end_headers(); self.wfile.write(resp)
        except Exception as exc:
            err = json.dumps({"ok": False, "route": route, "error": f"{type(exc).__name__}: {exc}"}).encode("utf-8")
            self.send_response(502); self._cors(); self.send_header("Content-Type", "application/json"); self.end_headers(); self.wfile.write(err)

if __name__ == "__main__":
    srv = HTTPServer(("0.0.0.0", PORT), PenguinHandler)
    print(f"MasiDyn Crostini penguin bridge listening on http://penguin.linux.test:{PORT} (0.0.0.0:{PORT})", flush=True)
    srv.serve_forever()
PYEOF
chmod +x "$HOME_DIR/penguin_bridge_daemon.py"

# 3. Install `masidyn-penguin-bridge` and `masidyn-penguin` launchers
cat > "$BIN_DIR/masidyn-penguin-bridge" <<EOF
#!/usr/bin/env bash
exec "$PY" "$HOME_DIR/penguin_bridge_daemon.py" "\$@"
EOF
chmod +x "$BIN_DIR/masidyn-penguin-bridge"

cat > "$BIN_DIR/masidyn-penguin" <<EOF
#!/usr/bin/env bash
# MasiDyn Chromebook (Crostini penguin) On-the-Go CLI launcher
export MASIDYN_CHROMEBOOK_MODE=1
export MASIDYN_PENGUIN_BRIDGE="http://penguin.linux.test:$BRIDGE_PORT"
if [ "\${1:-}" = "--bridge" ] || [ "\${1:-}" = "bridge" ]; then
  shift
  exec "$PY" "$HOME_DIR/penguin_bridge_daemon.py" "\$@"
fi
if [ -f "$HOME_DIR/masidyn_pick.py" ]; then
  exec "$PY" "$HOME_DIR/masidyn_pick.py" "\$@"
elif [ -f "$HOME_DIR/masidyn_chat.py" ]; then
  exec "$PY" "$HOME_DIR/masidyn_chat.py" "\$@"
else
  exec "$PY" "$HOME_DIR/penguin_bridge_daemon.py" "\$@"
fi
EOF
chmod +x "$BIN_DIR/masidyn-penguin"
cp "$BIN_DIR/masidyn-penguin" "$BIN_DIR/masidyn"
chmod +x "$BIN_DIR/masidyn"

say "Installed Crostini CLI: $BIN_DIR/masidyn-penguin (and $BIN_DIR/masidyn)"
say "Installed Native ChromeOS Bridge: $BIN_DIR/masidyn-penguin-bridge (http://penguin.linux.test:$BRIDGE_PORT)"
say "Ready for On-the-Go Chromebook operation! Run: masidyn-penguin"
