#!/usr/bin/env python3
"""
NectarGateway Status Checker — Launcher
Run: python3 launch.py
"""

import sys, os, threading, time, webbrowser, socket
from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer

import apikeys
from proxy_server import ProxyHandler  # shared with the production service — see proxy_server.py

PROXY_PORT  = 5050
STATIC_PORT = 5051

TOOLS = [
    { 'label': 'Nectar Status Checker',  'file': 'nectar_status_checker.html' },
    { 'label': 'Global Status Checker',  'file': 'global_status_checker.html' },
    { 'label': 'Both',                   'file': None },
]

class QuietHandler(SimpleHTTPRequestHandler):
    protocol_version = 'HTTP/1.0'
    def log_message(self, *a): pass
    def log_request(self, *a): pass

def ensure_local_dev_key():
    """First run on a machine: mint a 'local-dev' key so the tool works
    immediately, and print it so the person can paste it into the HTML tool's
    API key field. Safe to call every run — it's a no-op once a key exists."""
    if apikeys.has_any_active_key():
        return None
    key = apikeys.generate_key('local-dev')
    print("\n" + "=" * 60)
    print("First run — generated a local API key:")
    print(f"\n    {key}\n")
    print("Paste this into the 'API Key' field in the status checker tool.")
    print("Manage keys anytime with: python3 scripts/manage_keys.py list")
    print("=" * 60 + "\n")
    return key

def port_free(p):
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        return s.connect_ex(('localhost', p)) != 0

def wait_for_port(p, timeout=5):
    start = time.time()
    while time.time() - start < timeout:
        if not port_free(p):
            return True
        time.sleep(0.1)
    return False

def start_proxy():
    server = ThreadingHTTPServer(('localhost', PROXY_PORT), ProxyHandler)
    t = threading.Thread(target=server.serve_forever, daemon=True)
    t.start()
    return server

def start_static(directory):
    os.chdir(directory)
    server = ThreadingHTTPServer(('localhost', STATIC_PORT), QuietHandler)
    t = threading.Thread(target=server.serve_forever, daemon=True)
    t.start()
    return server

def main():
    here = os.path.dirname(os.path.abspath(__file__))

    missing = [t['file'] for t in TOOLS[:2] if t['file'] and not os.path.exists(os.path.join(here, t['file']))]
    if missing:
        print(f"Missing files: {', '.join(missing)}")
        print("Keep launch.py in the same folder as the HTML files.")
        input("Press Enter to exit.")
        sys.exit(1)

    print("\nNectarGateway Status Checker")
    print("=" * 36)
    for i, t in enumerate(TOOLS):
        print(f"  {i+1}. {t['label']}")
    print()

    ensure_local_dev_key()

    while True:
        choice = input("Select [1/2/3]: ").strip()
        if choice in ('1', '2', '3'):
            break

    tool = TOOLS[int(choice) - 1]

    # Start proxy
    if port_free(PROXY_PORT):
        start_proxy()
        if wait_for_port(PROXY_PORT):
            print(f"✓ Proxy on http://localhost:{PROXY_PORT}")
        else:
            print(f"✗ Proxy failed to start on port {PROXY_PORT}")
            sys.exit(1)
    else:
        print(f"Port {PROXY_PORT} already in use — proxy may already be running.")

    # Start static file server
    if port_free(STATIC_PORT):
        start_static(here)
        if wait_for_port(STATIC_PORT):
            print(f"✓ File server on http://localhost:{STATIC_PORT}")
        else:
            print(f"✗ File server failed to start on port {STATIC_PORT}")
            sys.exit(1)
    else:
        print(f"Port {STATIC_PORT} in use — using existing server.")

    # Small buffer to ensure servers are fully ready
    time.sleep(0.5)

    def open_tool(fname):
        url = f'http://localhost:{STATIC_PORT}/{fname}'
        print(f"✓ Opening {url}")
        webbrowser.open(url)

    if tool['file']:
        open_tool(tool['file'])
    else:
        open_tool(TOOLS[0]['file'])
        time.sleep(0.4)
        open_tool(TOOLS[1]['file'])

    print(f"\nRunning — keep this window open.")
    print("Press Ctrl+C to stop.\n")

    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        print("\nStopped.")

if __name__ == '__main__':
    main()
