"""
CARL Control Panel - Main entry point for pip install.
Uses pywebview for native window experience.
"""
import os
import sys
import threading
import time

# Server config
PORT = 5050
SERVER_URL = f"http://127.0.0.1:{PORT}/"

# Global state
flask_thread = None
webview_window = None
tray_icon = None

# Platform detection
IS_WINDOWS = sys.platform == 'win32'
IS_MAC = sys.platform == 'darwin'


def start_flask_server(app, init_database, load_active_profile):
    """Start the Flask server in the current thread."""
    try:
        init_database()
        load_active_profile()
        app.run(host='127.0.0.1', port=PORT, debug=False, use_reloader=False, threaded=True)
    except Exception as e:
        print(f"Flask server error: {e}")


def wait_for_server(timeout=30):
    """Wait for server to be ready."""
    import urllib.request
    import urllib.error

    start = time.time()
    while time.time() - start < timeout:
        try:
            urllib.request.urlopen(SERVER_URL, timeout=1)
            return True
        except (urllib.error.URLError, Exception):
            time.sleep(0.3)
    return False


def create_icon_image():
    """Create a warm amber/gold icon for system tray."""
    try:
        from PIL import Image, ImageDraw
        size = 64
        img = Image.new('RGBA', (size, size), (0, 0, 0, 0))
        draw = ImageDraw.Draw(img)
        draw.ellipse([2, 2, size-2, size-2], fill=(13, 13, 15, 255))
        amber = (212, 163, 115, 255)
        draw.arc([12, 12, size-12, size-12], start=45, end=315, fill=amber, width=8)
        return img
    except Exception:
        return None


def focus_window(icon=None, item=None):
    """Bring PyWebView window to focus."""
    global webview_window
    if webview_window:
        try:
            webview_window.show()
            webview_window.restore()
            webview_window.on_top = True
            webview_window.on_top = False
        except Exception:
            pass


def quit_app(icon=None, item=None):
    """Quit the application."""
    global tray_icon, webview_window

    if webview_window:
        try:
            webview_window.destroy()
        except Exception:
            pass

    if tray_icon:
        try:
            tray_icon.stop()
        except Exception:
            pass

    sys.exit(0)


def setup_tray():
    """Setup system tray icon."""
    global tray_icon

    try:
        import pystray
        from pystray import MenuItem as item
    except ImportError:
        print("[TRAY] pystray not available, skipping tray icon")
        return None

    icon_image = create_icon_image()
    if not icon_image:
        return None

    menu = pystray.Menu(
        item('Open CARL', focus_window, default=True),
        item('Server Running', lambda: None, enabled=False),
        pystray.Menu.SEPARATOR,
        item('Quit', quit_app)
    )

    tray_icon = pystray.Icon(
        'carl-control-panel',
        icon_image,
        'CARL Control Panel',
        menu
    )

    return tray_icon


def main():
    """Main entry point."""
    global flask_thread, webview_window, tray_icon

    # Change to package directory so Flask finds templates/static
    package_dir = os.path.dirname(os.path.abspath(__file__))
    os.chdir(package_dir)

    print("CARL Control Panel starting...")

    # Import here to ensure correct working directory
    from carl_control_panel.app import app, init_database, load_active_profile

    # Start Flask server in background thread
    flask_thread = threading.Thread(
        target=start_flask_server,
        args=(app, init_database, load_active_profile),
        daemon=True
    )
    flask_thread.start()

    # Wait for server to be ready
    print("Waiting for server...")
    if wait_for_server(timeout=30):
        print("Server ready!")
    else:
        print("Warning: Server may have failed to start")

    # Setup system tray in background
    tray_icon = setup_tray()
    if tray_icon:
        tray_thread = threading.Thread(target=tray_icon.run, daemon=True)
        tray_thread.start()

    # Create and show pywebview window
    try:
        import webview

        webview_window = webview.create_window(
            'CARL Control Panel',
            SERVER_URL,
            width=650,
            height=700,
            min_size=(500, 400),
            text_select=True,
            easy_drag=False,
            zoomable=True
        )

        # Start webview (this blocks until window is closed)
        if IS_WINDOWS:
            try:
                webview.start(gui='edgechromium')
            except Exception:
                webview.start()
        else:
            webview.start()

    except ImportError:
        # Fallback to browser if pywebview not available
        print("pywebview not available, opening in browser...")
        import webbrowser
        webbrowser.open(SERVER_URL)

        # Keep running until Ctrl+C
        try:
            while True:
                time.sleep(1)
        except KeyboardInterrupt:
            pass

    except Exception as e:
        print(f"Failed to start webview: {e}")
        print("Opening in browser instead...")
        import webbrowser
        webbrowser.open(SERVER_URL)

        try:
            while True:
                time.sleep(1)
        except KeyboardInterrupt:
            pass

    # Cleanup
    quit_app()


if __name__ == "__main__":
    main()
