"""Convenience launcher: local server, readiness check and default browser."""
from pathlib import Path
import json
import subprocess
import sys
import time
import urllib.request
import webbrowser

root=Path(__file__).resolve().parents[1]
url='http://127.0.0.1:8787'
server=subprocess.Popen([sys.executable,str(root/'run.py')],cwd=root)
try:
    for attempt in range(40):
        time.sleep(0.2)
        if server.poll() is not None:
            raise RuntimeError('Server did not start. If port 8787 is busy, stop the other local copy first.')
        try:
            with urllib.request.urlopen(url+'/api/health',timeout=1) as response:
                ready=json.load(response).get('mode')=='local-demo'
            if ready:
                break
        except OSError:
            pass
    else:
        raise RuntimeError('The local server did not become ready.')
    print('\nOpen '+url+'\nKeep this window open. Press Control-C here to stop the app.\n',flush=True)
    if '--no-browser' not in sys.argv:
        webbrowser.open(url)
    server.wait()
except KeyboardInterrupt:
    print('\nStopping the local prototype.',flush=True)
except Exception as error:
    print(str(error),file=sys.stderr)
    sys.exit(1)
finally:
    if server.poll() is None:
        server.terminate()
        try:
            server.wait(timeout=5)
        except subprocess.TimeoutExpired:
            server.kill()
            server.wait()
