#!/usr/bin/env bash
# ==============================================================================
# HROS v3.1 — The Human Router Operating System
# Sovereign Bare-Metal Installer & Node Bootstrap Suite
# USPTO Patent #63/900,179 | WeRAI AI Integration Inc.
# "Power needs ground. You keep everything. G=1. Always."
# ==============================================================================

set -e

CYAN="\033[0;36m"
GOLD="\033[0;33m"
GREEN="\033[0;32m"
BLUE="\033[0;34m"
RED="\033[0;31m"
BOLD="\033[1m"
NC="\033[0m"

clear 2>/dev/null || true
echo -e "${CYAN}"
cat << "BANNER"
  _    _ _____   ____   _____           ____  _ 
 | |  | |  __ \ / __ \ / ____|  __   _|___ \/ |
 | |__| | |__) | |  | | (___   _\ \ / / __) | |
 |  __  |  _  /| |  | |\___ \ (_) \ V /|__ <| |
 | |  | | | \ \| |__| |____) |     | | ___) | |
 |_|  |_|_|  \_\\____/|_____/      |_||____/|_|
                                               
  SOVEREIGN BARE-METAL HUMAN ROUTER OPERATING SYSTEM
  USPTO Patent #63/900,179 | WeRAI AI Integration Inc.
BANNER
echo -e "${NC}"

echo -e "${BOLD}${GOLD}>> [1/6] Preparing Sovereign Environment & Storage Topology...${NC}"

# Detect Python
if ! command -v python3 &> /dev/null; then
    echo -e "${RED}✗ python3 is required but not installed.${NC}"
    if command -v apt-get &> /dev/null; then
        echo -e "${CYAN}Attempting to install python3...${NC}"
        sudo apt-get update && sudo apt-get install -y python3 python3-pip
    elif command -v dnf &> /dev/null; then
        sudo dnf install -y python3 python3-pip
    elif command -v pacman &> /dev/null; then
        sudo pacman -Sy --noconfirm python python-pip
    else
        echo -e "${RED}Please install python3 using your package manager and rerun.${NC}"
        exit 1
    fi
fi

# Create directories
mkdir -p "$HOME/ZERR/vault"
mkdir -p "$HOME/ZERR/evidence"
mkdir -p "$HOME/ZERR/memory"
mkdir -p "$HOME/ZERR/config"
mkdir -p "$HOME/.hros/bin"
mkdir -p "$HOME/.hros/logs"
mkdir -p "$HOME/.local/bin"
mkdir -p "$HOME/.local/share/applications"

# Ensure PATH inclusion across all common shells
for profile_file in "$HOME/.bashrc" "$HOME/.profile" "$HOME/.zshrc"; do
    if [ -f "$profile_file" ]; then
        if ! grep -q "\.hros/bin" "$profile_file"; then
            echo 'export PATH="$HOME/.hros/bin:$HOME/.local/bin:$PATH"' >> "$profile_file"
        fi
    fi
done
export PATH="$HOME/.hros/bin:$HOME/.local/bin:$PATH"

# Generate or preserve Node ID
if [ ! -f "$HOME/ZERR/node.conf" ]; then
    NODE_ID=$(head -c 16 /dev/urandom | xxd -p 2>/dev/null || od -vAn -N16 -tx1 /dev/urandom 2>/dev/null | tr -d " \n" || date +%s%N)
    TIMESTAMP=$(date -u +"%Y-%m-%dT%H:%M:%SZ")
    cat << EOF_CONF > "$HOME/ZERR/node.conf"
# HROS Sovereign Node Configuration
NODE_UUID="${NODE_ID}"
INITIALIZED_AT="${TIMESTAMP}"
SOVEREIGN_STATUS="ACTIVE"
G_GATE="1"
TELEMETRY="DISABLED"
CLOUD_TETHER="AIR_GAPPED"
EOF_CONF
    echo -e "${GREEN}✓ Provisioned new sovereign identity: Node UUID [${NODE_ID:0:8}...]${NC}"
else
    echo -e "${GREEN}✓ Existing sovereign node configuration preserved at ~/ZERR/node.conf${NC}"
fi

echo -e "\n${BOLD}${GOLD}>> [2/6] Detecting Hardware Acceleration & Compute Substrate...${NC}"
if command -v nvidia-smi &> /dev/null && nvidia-smi &> /dev/null; then
    GPU_NAME=$(nvidia-smi --query-gpu=name --format=csv,noheader | head -n 1 2>/dev/null || echo "NVIDIA GPU")
    GPU_MEM=$(nvidia-smi --query-gpu=memory.total --format=csv,noheader | head -n 1 2>/dev/null || echo "Available")
    echo -e "${GREEN}✓ Hardware Acceleration: ${GPU_NAME} (${GPU_MEM})${NC}"
else
    CPU_CORES=$(grep -c ^processor /proc/cpuinfo 2>/dev/null || sysctl -n hw.ncpu 2>/dev/null || echo "4")
    echo -e "${CYAN}ℹ Host Compute: CPU Multi-Core Engine (${CPU_CORES} cores detected)${NC}"
fi

echo -e "\n${BOLD}${GOLD}>> [3/6] Setting Up Local Ollama AI Engine...${NC}"
if ! command -v ollama &> /dev/null; then
    echo -e "${CYAN}Installing on-device Ollama runtime...${NC}"
    curl -fsSL https://ollama.com/install.sh | sh || true
fi

if command -v ollama &> /dev/null; then
    echo -e "${GREEN}✓ Ollama engine installed.${NC}"
    # Ensure Ollama daemon is running
    if ! curl -s http://127.0.0.1:11434/api/tags &>/dev/null; then
        echo -e "${CYAN}Starting Ollama local service...${NC}"
        sudo systemctl start ollama 2>/dev/null || (ollama serve > "$HOME/.hros/logs/ollama.log" 2>&1 &)
        sleep 2
    fi
    if curl -s http://127.0.0.1:11434/api/tags &>/dev/null; then
        echo -e "${GREEN}✓ Ollama service verified and responding on http://127.0.0.1:11434${NC}"
    else
        echo -e "${GOLD}⚠ Ollama service starting in background.${NC}"
    fi
else
    echo -e "${GOLD}⚠ Please ensure Ollama is installed manually if automated install was skipped.${NC}"
fi

echo -e "\n${BOLD}${GOLD}>> [4/6] Checking Local AI Models...${NC}"
AVAILABLE_MODELS=$(curl -s http://127.0.0.1:11434/api/tags 2>/dev/null | grep -o '"name":"[^"]*"' | cut -d'"' -f4 || true)
if [ -n "$AVAILABLE_MODELS" ]; then
    echo -e "${GREEN}✓ Active local models detected:${NC}"
    for m in $AVAILABLE_MODELS; do
        echo -e "   • ${m}"
    done
else
    echo -e "${CYAN}No models detected yet. Pulling recommended sovereign model (llama3.2:3b)...${NC}"
    if command -v ollama &>/dev/null; then
        ollama pull llama3.2:3b || ollama pull llama3.2:1b || true
    fi
fi

echo -e "\n${BOLD}${GOLD}>> [5/6] Installing Sovereign HROS Unified CLI & G=1 Consent Gate...${NC}"

# Deploy G=1 Gate script
cat << 'EOF_G1' > "$HOME/.hros/bin/g1-gate"
#!/usr/bin/env bash
# ==============================================================================
# G=1 Deterministic Hardware & Execution Consent Boundary
# USPTO Patent #63/900,179
# ==============================================================================
echo "[G=1 GATE] Deterministic Human Consent Boundary: ACTIVE"
if [ -f "$HOME/ZERR/node.conf" ]; then
    NODE_UUID=$(grep NODE_UUID "$HOME/ZERR/node.conf" | cut -d'=' -f2 | tr -d '"')
    echo "[G=1 GATE] Authenticated Node: ${NODE_UUID}"
    echo "[G=1 GATE] Human Authority: Preserved (No unverified autonomous mutations)"
    exit 0
else
    echo "[G=1 GATE] Refused: Sovereign node configuration not found."
    exit 1
fi
EOF_G1
chmod +x "$HOME/.hros/bin/g1-gate"

# Deploy Standalone Unified HROS CLI
cat << 'EOF_HROS' > "$HOME/.hros/bin/hros"
#!/usr/bin/env python3
"""
HROS Unified Sovereign CLI (Human Router Operating System)
USPTO Patent #63/900,179 | WeRAI AI Integration Inc.
Zero-dependency, bare-metal local AI co-pilot and system governor.
"""

import sys
import os
import json
import urllib.request
import urllib.error
import subprocess
import time

OLLAMA_HOST = os.environ.get("OLLAMA_HOST", "http://127.0.0.1:11434")

CYAN = "\033[0;36m"
GOLD = "\033[0;33m"
GREEN = "\033[0;32m"
RED = "\033[0;31m"
BOLD = "\033[1m"
DIM = "\033[2m"
NC = "\033[0m"

SYSTEM_PROMPT = """You are HROS (Human Router Operating System), a sovereign, local-first on-device AI co-pilot engineered by WeRAI AI Integration Inc. 
You run directly on local silicon under deterministic human authority (G=1).
You prioritize privacy, user sovereignty, concise execution, and direct actionable reasoning.
You never send user data to remote clouds without explicit user consent."""

def get_installed_models():
    try:
        req = urllib.request.Request(f"{OLLAMA_HOST}/api/tags")
        with urllib.request.urlopen(req, timeout=3) as r:
            data = json.loads(r.read().decode())
            return [m["name"] for m in data.get("models", [])]
    except Exception:
        return []

def select_default_model(models):
    if not models:
        return "llama3.2:latest"
    for pref in ["llama3.2:3b", "llama3.2:latest", "llama3.1:8b", "phi4", "phi3", "mistral"]:
        for m in models:
            if pref in m:
                return m
    return models[0]

def stream_chat(model, prompt, history=None):
    if history is None:
        history = []
    
    messages = [{"role": "system", "content": SYSTEM_PROMPT}]
    messages.extend(history)
    messages.append({"role": "user", "content": prompt})
    
    payload = json.dumps({
        "model": model,
        "messages": messages,
        "stream": True
    }).encode("utf-8")
    
    req = urllib.request.Request(
        f"{OLLAMA_HOST}/api/chat",
        data=payload,
        headers={"Content-Type": "application/json"}
    )
    
    assistant_reply = []
    try:
        with urllib.request.urlopen(req, timeout=120) as resp:
            for line in resp:
                if line:
                    obj = json.loads(line.decode("utf-8"))
                    token = obj.get("message", {}).get("content", "")
                    sys.stdout.write(token)
                    sys.stdout.flush()
                    assistant_reply.append(token)
        print()
    except urllib.error.URLError as e:
        print(f"\n{RED}Error communicating with local Ollama: {e}{NC}")
        print(f"{DIM}Ensure Ollama is running: ollama serve{NC}")
    except KeyboardInterrupt:
        print(f"\n{GOLD}[Interrupted by human authority]{NC}")
    
    return "".join(assistant_reply)

def interactive_repl(model):
    print(f"{CYAN}{BOLD}=============================================================================={NC}")
    print(f"{CYAN}{BOLD}  🐉 HROS Sovereign Terminal Co-Pilot (v3.1){NC}")
    print(f"{DIM}  Model: {model} | Silicon: Local Engine | Boundary: G=1 Deterministic{NC}")
    print(f"{DIM}  Type 'exit', 'quit', or Ctrl+C to close session.{NC}")
    print(f"{CYAN}{BOLD}=============================================================================={NC}\n")
    
    history = []
    while True:
        try:
            prompt = input(f"{GREEN}{BOLD}HROS > {NC}").strip()
            if not prompt:
                continue
            if prompt.lower() in ["exit", "quit", ":q"]:
                print(f"{GOLD}Sovereign session ended. G=1. Always.{NC}")
                break
            
            print(f"{CYAN}{BOLD}AI >> {NC}", end="", flush=True)
            reply = stream_chat(model, prompt, history)
            if reply:
                history.append({"role": "user", "content": prompt})
                history.append({"role": "assistant", "content": reply})
                if len(history) > 20:
                    history = history[-20:]
            print()
        except (KeyboardInterrupt, EOFError):
            print(f"\n{GOLD}Exiting HROS session. Take care.{NC}")
            break

def show_status():
    print(f"{CYAN}{BOLD}=============================================================================={NC}")
    print(f"{CYAN}{BOLD}  HROS v3.1 Sovereign Substrate Telemetry{NC}")
    print(f"{CYAN}{BOLD}=============================================================================={NC}")
    
    node_conf = os.path.expanduser("~/ZERR/node.conf")
    if os.path.exists(node_conf):
        with open(node_conf) as f:
            for line in f:
                if "=" in line:
                    k, v = line.strip().split("=", 1)
                    print(f"  {BOLD}{k:20}{NC}: {v.strip('\"')}")
    else:
        print(f"  {RED}ZERR Node Config    : Not found (Run hros-install.sh){NC}")
    
    models = get_installed_models()
    print(f"  {BOLD}{'Ollama Engine':20}{NC}: {'ONLINE' if models is not None else 'OFFLINE'}")
    print(f"  {BOLD}{'Local Models':20}{NC}: {', '.join(models) if models else 'None installed'}")
    print(f"  {BOLD}{'G=1 Runtime Gate':20}{NC}: ENFORCED (USPTO #63/900,179)")
    print(f"{CYAN}=============================================================================={NC}")

def pull_model(model_name):
    print(f"{CYAN}Pulling model {model_name} via local Ollama...{NC}")
    subprocess.run(["ollama", "pull", model_name])

def main():
    args = sys.argv[1:]
    
    if not args:
        models = get_installed_models()
        model = select_default_model(models)
        interactive_repl(model)
        return
        
    cmd = args[0].lower()
    
    if cmd in ["status", "--status", "-s"]:
        show_status()
        return
        
    if cmd in ["models", "--models", "list", "-l"]:
        models = get_installed_models()
        print(f"{BOLD}Installed Local Models:{NC}")
        for m in models:
            print(f"  • {m}")
        return
        
    if cmd in ["gate", "--gate", "-g"]:
        gate_script = os.path.expanduser("~/.hros/bin/g1-gate")
        if os.path.exists(gate_script):
            os.system(gate_script)
        else:
            print("[G=1 GATE] Enforced.")
        return
        
    if cmd in ["version", "--version", "-v"]:
        print("HROS v3.1 Sovereign (USPTO Patent #63/900,179)")
        return
        
    if cmd == "pull" and len(args) > 1:
        pull_model(args[1])
        return

    if cmd in ["ask", "prompt"] and len(args) > 1:
        models = get_installed_models()
        model = select_default_model(models)
        prompt_text = " ".join(args[1:])
        print(f"{CYAN}{BOLD}⚡ [{model}] > {DIM}{prompt_text}{NC}")
        stream_chat(model, prompt_text)
        return
        
    if cmd in ["chat", "repl"]:
        models = get_installed_models()
        model = select_default_model(models)
        interactive_repl(model)
        return
        
    # Default: treat all args as a direct prompt
    models = get_installed_models()
    model = select_default_model(models)
    prompt_text = " ".join(args)
    print(f"{CYAN}{BOLD}⚡ [{model}] > {DIM}{prompt_text}{NC}")
    stream_chat(model, prompt_text)

if __name__ == "__main__":
    main()
EOF_HROS

chmod +x "$HOME/.hros/bin/hros"

# Copy to ~/.local/bin
cp "$HOME/.hros/bin/hros" "$HOME/.local/bin/hros"
cp "$HOME/.hros/bin/g1-gate" "$HOME/.local/bin/g1-gate"

# If sudo available without prompt, install to /usr/local/bin for global system access
if sudo -n true 2>/dev/null; then
    sudo cp "$HOME/.hros/bin/hros" /usr/local/bin/hros 2>/dev/null || true
    sudo cp "$HOME/.hros/bin/g1-gate" /usr/local/bin/g1-gate 2>/dev/null || true
    echo -e "${GREEN}✓ Global system command installed: /usr/local/bin/hros${NC}"
else
    echo -e "${GREEN}✓ User command installed: ~/.local/bin/hros${NC}"
fi

echo -e "\n${BOLD}${GOLD}>> [6/6] Creating Desktop Application Shortcut...${NC}"
cat << EOF_DESKTOP > "$HOME/.local/share/applications/hros.desktop"
[Desktop Entry]
Version=1.0
Type=Application
Name=HROS Sovereign Terminal
Comment=Human Router Operating System — On-Device AI Co-Pilot
Exec=bash -c "hros; exec bash"
Icon=utilities-terminal
Terminal=true
Categories=Development;System;Utility;
StartupNotify=true
EOF_DESKTOP
chmod +x "$HOME/.local/share/applications/hros.desktop"

# If Desktop folder exists, put a shortcut on Desktop
if [ -d "$HOME/Desktop" ]; then
    cp "$HOME/.local/share/applications/hros.desktop" "$HOME/Desktop/HROS_Terminal.desktop"
    chmod +x "$HOME/Desktop/HROS_Terminal.desktop"
    gio set "$HOME/Desktop/HROS_Terminal.desktop" metadata::trusted true 2>/dev/null || true
    echo -e "${GREEN}✓ Desktop launcher created: ~/Desktop/HROS_Terminal.desktop${NC}"
fi

echo -e "\n${CYAN}==============================================================================${NC}"
cat << "OATH"
THE SOVEREIGN OATH:
I will not extract from others what was not freely given.
I will help when I can. No guilt when I can't.
My node is mine. My data is mine. My compute is mine.
I am transparent like glass and hard like steel.
Every 1 and 0 is documented — Human, AI, and Other.
OATH
echo -e "${CYAN}==============================================================================${NC}"

echo -e "\n${GREEN}${BOLD}🎉 HROS INSTALLATION COMPLETE!${NC}"
echo -e "${BOLD}Your machine is now operating under Sovereign Human Authority.${NC}"
echo -e "\n${GOLD}Quick Start Commands:${NC}"
echo -e "  • ${BOLD}hros${NC}                  - Launch interactive local AI co-pilot"
echo -e "  • ${BOLD}hros ask \"question\"${NC}   - Ask a quick question directly from terminal"
echo -e "  • ${BOLD}hros status${NC}           - Display hardware, GPU, and node telemetry"
echo -e "  • ${BOLD}hros models${NC}           - List all installed local models"
echo -e "  • ${BOLD}hros gate${NC}             - Verify G=1 deterministic consent gate"
echo -e "\n${CYAN}G=1. Always. 🐉${NC}\n"
