"""Start the development server with host and port from config.yaml.

Reads server.host and server.port from config/config.yaml via the project's
config loader, runs ``manage.py runserver <host>:<port>``, and opens a browser
to http://127.0.0.1:<port> .

Usage (by run.bat):
    start /B runtime\\python\\python.exe scripts\\start_server.py
"""

import subprocess
import sys
import webbrowser
from pathlib import Path

_project_root = Path(__file__).resolve().parent.parent
if str(_project_root) not in sys.path:
    sys.path.insert(0, str(_project_root))

from config import get_config


def main() -> None:
    cfg = get_config()

    host = cfg.server.host or '0.0.0.0'
    port = cfg.server.port or 80

    addr = f'{host}:{port}'
    manage_py = Path(__file__).resolve().parent.parent / 'manage.py'

    # Open browser — use 127.0.0.1 regardless of bind address so the user's
    # browser always reaches the local machine.
    webbrowser.open(f'http://127.0.0.1:{port}/')

    # Run the server.  subprocess.call is blocking, so this script stays alive
    # as long as the dev server does — the same effect as calling manage.py
    # directly under start /B.
    sys.exit(subprocess.call([sys.executable, str(manage_py), 'runserver', addr, '--noreload']))


if __name__ == '__main__':
    main()
