#!python
"""OpenGate headless server launcher.

Production analog of the client's GUI ``launcher``: it obtains the game assets
(clone on first run, pull to refresh) and then starts the server. This is the
entry point a container or an init system invokes so a fresh host becomes
runnable without a manual ``git submodule``/``clone`` step.

Usage
-----
    ./og-server-launcher [--no-update] [--assets-ref REF] [server args...]

All arguments other than the launcher's own (``--no-update``, ``--assets-ref``)
are passed straight through to ``Opengate.server.main`` (host, port, metrics,
bots, ...), so this is a drop-in front end for ``og-server``.

Equivalent to obtaining assets, then ``python -m Opengate.server``.
"""

import sys
import os
import argparse

sys.path.append("./")
os.environ["PYGAME_HIDE_SUPPORT_PROMPT"] = "1"

from Opengate.server.launcher import ensure_assets, AssetProvisionError


def main() -> None:
    """Provision assets, then hand off to the server entry point."""
    # Parse only the launcher's own flags; leave everything else for the
    # server's own argparse in Opengate.server.main. ``parse_known_args``
    # returns the unrecognised args so we can restore them onto sys.argv.
    parser = argparse.ArgumentParser(
        description="OpenGate headless server launcher",
        add_help=False,  # let the server own -h so its full usage is shown
    )
    parser.add_argument(
        "--no-update",
        dest="update",
        action="store_false",
        help="Skip obtaining/updating assets before start",
    )
    parser.add_argument(
        "--assets-ref",
        dest="assets_ref",
        type=str,
        default=None,
        help="Assets branch/tag/commit to check out (default: remote's latest)",
    )
    args, passthrough = parser.parse_known_args()

    if args.update:
        try:
            ensure_assets(ref=args.assets_ref)
        except AssetProvisionError:
            # ensure_assets already logged the reason in red.
            raise SystemExit(1) from None

    # Rebuild argv for the server: program name + the untouched passthrough
    # args (host/port/metrics/bots/...).
    sys.argv = [sys.argv[0], *passthrough]

    from Opengate.server import main as server_main

    server_main()


if __name__ == "__main__":
    main()
