#!/bin/bash
# OpsCore Demo Launcher — Linux
# Run: bash START_OPSCORE_DEMO_LINUX.sh

clear
echo ""
echo "  ============================================"
echo "    OpsCore — One-Click Demo Launcher"
echo "    Private Business Operating System"
echo "  ============================================"
echo ""

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
DEMO_DIR="/tmp/opscore_demo"

mkdir -p "$DEMO_DIR"
cp -f "$SCRIPT_DIR/offline.html" "$DEMO_DIR/index.html" 2>/dev/null || true
cp -f "$SCRIPT_DIR/offline.html" "$DEMO_DIR/offline.html" 2>/dev/null || true

# Detect Python
if command -v python3 &>/dev/null; then
    PYTHON=python3
elif command -v python &>/dev/null; then
    PYTHON=python
else
    echo "  Python not found."
    # Try xdg-open for offline fallback
    if command -v xdg-open &>/dev/null; then
        echo "  Opening offline demo with xdg-open..."
        xdg-open "$SCRIPT_DIR/offline.html"
    else
        echo "  Open this file in your browser manually:"
        echo "  $SCRIPT_DIR/offline.html"
    fi
    exit 0
fi

# Write Python server
cat > "$DEMO_DIR/serve.py" << 'PYEOF'
import http.server, os, sys, subprocess

PORT = 8080
DEMO_DIR = os.path.dirname(os.path.abspath(__file__))
os.chdir(DEMO_DIR)

def open_browser(url):
    for cmd in ['xdg-open', 'sensible-browser', 'gnome-open', 'firefox', 'chromium-browser']:
        try:
            subprocess.Popen([cmd, url], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
            return
        except FileNotFoundError:
            continue

class DemoHandler(http.server.SimpleHTTPRequestHandler):
    def do_GET(self):
        if self.path in ('/', ''):
            self.path = '/offline.html'
        super().do_GET()
    def log_message(self, *args):
        pass

print("  OpsCore demo: http://localhost:8080")
print("  Press Ctrl+C to stop.")
open_browser('http://localhost:8080')
http.server.HTTPServer(('', PORT), DemoHandler).serve_forever()
PYEOF

echo "  [OK] Demo files ready"
echo "  [OK] Starting server on http://localhost:8080"
echo "  [OK] Opening browser..."
echo ""
echo "  License: FREE_DEMO_UNLIMITED | Dataset: Shelter Housing Group | 19 Modules"
echo ""
echo "  Ctrl+C to stop."
echo ""

$PYTHON "$DEMO_DIR/serve.py"
