#!/usr/bin/env python3
"""Enter an allocated pseudo-terminal and invoke the real MMO TUI launcher."""

from __future__ import annotations

import fcntl
import json
import os
import sys
import termios

from mmo_runtime import launch_interactive


def main() -> int:
    try:
        # Popen(start_new_session=True) made this process a session leader. The
        # slave PTY descriptors were inherited, so explicitly claim the terminal
        # before MMO performs normal foreground process-group handoff.
        fcntl.ioctl(sys.stdin.fileno(), termios.TIOCSCTTY, 0)
        os.tcsetpgrp(sys.stdin.fileno(), os.getpgrp())
        initial = termios.tcgetattr(sys.stdin.fileno())
        exit_code = launch_interactive(profile=sys.argv[1], cwd=sys.argv[2])
        restored = termios.tcgetattr(sys.stdin.fileno())
        print(
            json.dumps(
                {
                    "event": "launcher_returned",
                    "exit_code": exit_code,
                    "echo_enabled": bool(restored[3] & termios.ECHO),
                    "attributes_restored": restored == initial,
                    "pgrp": os.getpgrp(),
                    "foreground_pgrp": os.tcgetpgrp(sys.stdin.fileno()),
                },
                sort_keys=True,
            ),
            flush=True,
        )
        return exit_code
    except BaseException as exc:
        print(json.dumps({"event": "launcher_error", "error": repr(exc)}), flush=True)
        return 97


if __name__ == "__main__":
    raise SystemExit(main())
