#!/usr/bin/env python3
"""
Axiom Zero — Universal Dual-Engine GTK Launcher
Attempts to launch the GPU-accelerated GTK 4.14 Control Surface first.
If GTK 4 is missing on legacy distros, seamlessly falls back to GTK 3.
If running in a headless environment, launches the Headless Web / CLI Mode.
"""

import sys
import os
import logging

logging.basicConfig(level=logging.INFO, format="[Axiom Launcher] %(asctime)s - %(levelname)s - %(message)s")
logger = logging.getLogger("axiom_launcher")

SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
PROJECT_ROOT = os.path.abspath(os.path.join(SCRIPT_DIR, ".."))

if SCRIPT_DIR not in sys.path:
    sys.path.insert(0, SCRIPT_DIR)
if PROJECT_ROOT not in sys.path:
    sys.path.insert(0, PROJECT_ROOT)

def launch_control_surface():
    has_display = os.environ.get("DISPLAY") or os.environ.get("WAYLAND_DISPLAY") or os.environ.get("NOCTUA_HEADLESS_TEST")
    
    if not has_display and "--headless" not in sys.argv:
        logger.info("No DISPLAY environment variable detected. Running in Headless Mode...")
        # Run daemon in headless mode
        os.execv(sys.executable, [sys.executable, os.path.join(SCRIPT_DIR, "axiom_daemon.py")])
        return

    # Attempt GTK 4 First (Modern GPU-Accelerated Engine)
    try:
        import gi
        gi.require_version('Gtk', '4.0')
        from gi.repository import Gtk
        logger.info("⚡ GTK 4.14 detected! Launching GPU-Accelerated Control Surface...")
        import axiom_dev_control_gtk4
        app = axiom_dev_control_gtk4.AxiomDevControlGTK4()
        sys.exit(app.run(sys.argv))
    except (ImportError, ValueError) as e:
        logger.info(f"GTK 4 unavailable ({e}). Gracefully falling back to GTK 3...")
    
    # Fallback to GTK 3 (Universal Compatibility Engine)
    try:
        import gi
        gi.require_version('Gtk', '3.0')
        from gi.repository import Gtk
        logger.info("✓ GTK 3 initialized. Launching Universal Control Surface...")
        import axiom_dev_control_gtk
        app = axiom_dev_control_gtk.AxiomDevControlGTK()
        win = axiom_dev_control_gtk.AxiomDevControlGTK()
        Gtk.main()
    except Exception as e:
        logger.error(f"Failed to launch GTK 3 Control Surface: {e}")
        sys.exit(1)

if __name__ == "__main__":
    launch_control_surface()
