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

All output (stdout + stderr) is redirected to log files so the process
can run in the background without blocking any terminal.
"""

import os
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 8000
    addr = f'{host}:{port}'
    manage_py = _project_root / 'manage.py'

    # Log files — capture ALL output so nothing goes to console
    stdout_log = _project_root / 'server_stdout.txt'
    stderr_log = _project_root / 'server_stderr.txt'
    pid_file = _project_root / '.server_pid'

    # Write PID so run.bat can print it
    pid_file.write_text(str(os.getpid()), encoding='utf-8')

    # Open browser
    webbrowser.open(f'http://127.0.0.1:{port}/')

    # Run server with ALL output redirected to files
    with open(stdout_log, 'a', encoding='utf-8') as out_fh, \
         open(stderr_log, 'a', encoding='utf-8') as err_fh:
        rc = subprocess.call(
            [sys.executable, str(manage_py), 'runserver', addr, '--noreload'],
            stdout=out_fh,
            stderr=err_fh,
        )

    # Clean up PID file on exit
    try:
        pid_file.unlink(missing_ok=True)
    except Exception:
        pass

    sys.exit(rc)


if __name__ == '__main__':
    main()
