"""Mission Control local server — serves the dashboard and opens the browser.
Double-click this via the shortcut, or run: pythonw mission_control.py
"""
import http.server, functools, os, socket, threading, webbrowser, traceback

DIR = os.path.dirname(os.path.abspath(__file__))
HTML = "Hermes_Mission_Control.html"
PORT = 8777
LOG = os.path.join(DIR, "server.log")

def log(msg):
    with open(LOG, "a") as f:
        f.write(msg + "\n")

class Handler(http.server.SimpleHTTPRequestHandler):
    def log_message(self, format, *args):  # pythonw has no stderr — write to file instead
        log("%s - %s" % (self.address_string(), format % args))

def port_in_use(port):
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        s.settimeout(1)
        try:
            s.connect(("127.0.0.1", port))
            return True
        except OSError:
            return False

# ponytail: single-instance via port probe — if already serving, just open the tab.
if port_in_use(PORT):
    log("already serving, opening tab")
    webbrowser.open(f"http://127.0.0.1:{PORT}/{HTML}")
    raise SystemExit(0)

try:
    handler = functools.partial(Handler, directory=DIR)
    srv = http.server.ThreadingHTTPServer(("127.0.0.1", PORT), handler)
    log(f"serving on {PORT}")
except Exception:
    log("STARTUP ERROR:\n" + traceback.format_exc())
    raise

threading.Timer(0.5, lambda: webbrowser.open(f"http://127.0.0.1:{PORT}/{HTML}")).start()
print(f"Mission Control → http://127.0.0.1:{PORT}/{HTML}  (Ctrl+C to stop)")
srv.serve_forever()
