#!/usr/bin/env python3
"""
Nectar Status Checker — Launcher
Run: python3 nectar_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
HTML_FILE   = 'nectar_status_checker.html'

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():
    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 main():
    here = os.path.dirname(os.path.abspath(__file__))

    if not os.path.exists(os.path.join(here, HTML_FILE)):
        print(f"Missing: {HTML_FILE}")
        print("Keep nectar_launch.py in the same folder as nectar_status_checker.html")
        input("Press Enter to exit.")
        sys.exit(1)

    print("\nNectar Status Checker")
    print("=" * 28)

    ensure_local_dev_key()

    if port_free(PROXY_PORT):
        server = ThreadingHTTPServer(('localhost', PROXY_PORT), ProxyHandler)
        threading.Thread(target=server.serve_forever, daemon=True).start()
        if wait_for_port(PROXY_PORT):
            print(f"✓ Proxy on http://localhost:{PROXY_PORT}")
        else:
            print(f"✗ Proxy failed to start"); sys.exit(1)
    else:
        print(f"Port {PROXY_PORT} in use — proxy may already be running.")

    if port_free(STATIC_PORT):
        os.chdir(here)
        server = ThreadingHTTPServer(('localhost', STATIC_PORT), QuietHandler)
        threading.Thread(target=server.serve_forever, daemon=True).start()
        if wait_for_port(STATIC_PORT):
            print(f"✓ File server on http://localhost:{STATIC_PORT}")
        else:
            print(f"✗ File server failed to start"); sys.exit(1)
    else:
        print(f"Port {STATIC_PORT} in use — using existing server.")

    time.sleep(0.5)

    url = f'http://localhost:{STATIC_PORT}/{HTML_FILE}'
    print(f"✓ Opening {url}\n")
    webbrowser.open(url)

    print("Running — 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()
