"""Root-owned tmux client mediator for cross-UID seat control."""

from __future__ import annotations

import argparse
import os

from seat_common import CONTROL_RE, SEAT_ID_RE, die as _common_die
from seat_implementer_identity import (
    expected_socket_for_seat,
    resolve_implementer_for_seat,
)
from seat_scope_entry import resolve_target

INSTALLED_BIN = "/usr/local/bin/overdeck-seat-tmux-mediator"
ALLOWED_SUBCOMMANDS = frozenset({
    "attach-session",
    "list-panes",
    "has-session",
    "kill-server",
})


def die(msg: str, code: int = 2) -> None:
    _common_die(f"overdeck-seat-tmux-mediator: {msg}", code)


def validate_text(name: str, value: str) -> None:
    if not value or CONTROL_RE.search(value):
        die(f"invalid {name}")


def validate_socket(socket: str, operator_home: str, seat_id: str) -> None:
    want = expected_socket_for_seat(operator_home, seat_id)
    if socket != want:
        die("socket-mismatch", 1)
    if not socket.startswith("/") or "//" in socket:
        die("invalid socket", 1)
    if not os.path.exists(os.path.dirname(socket)):
        die("socket-parent-missing", 1)


def build_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(prog="overdeck-seat-tmux-mediator", add_help=True)
    parser.add_argument("--seat-id", required=True)
    parser.add_argument("--socket", required=True)
    parser.add_argument("tmux_args", nargs=argparse.REMAINDER)
    return parser


def validate_tmux_args(args: list[str]) -> list[str]:
    if not args:
        die("tmux-args-missing", 1)
    if args[0] == "--":
        args = args[1:]
    if not args:
        die("tmux-args-missing", 1)
    sub = args[0]
    if sub not in ALLOWED_SUBCOMMANDS:
        die(f"tmux-subcommand-forbidden:{sub}", 1)
    if "-S" in args:
        die("tmux-socket-flag-forbidden", 1)
    if "-L" in args:
        die("tmux-server-flag-forbidden", 1)
    return args


def run_tmux_as_implementer(
    implementer_user: str,
    socket: str,
    tmux_args: list[str],
    *,
    tmux: str = "tmux",
    sudo: str = "sudo",
) -> None:
    argv = [sudo, "-n", "-u", implementer_user, tmux, "-S", socket, *tmux_args]
    os.execvp(sudo, argv)


def main(argv: list[str] | None = None) -> None:
    parser = build_parser()
    try:
        ns = parser.parse_args(argv)
    except SystemExit:
        die("unknown arg", 2)

    if not SEAT_ID_RE.match(ns.seat_id):
        die("invalid seat id")

    if os.geteuid() != 0:
        die("requires root", 1)

    operator_user, _operator_uid, _operator_gid, operator_home = resolve_target()
    validate_socket(ns.socket, operator_home, ns.seat_id)
    implementer_user, _uid, _gid = resolve_implementer_for_seat(ns.seat_id, operator_user)
    tmux_args = validate_tmux_args(list(ns.tmux_args))
    run_tmux_as_implementer(implementer_user, ns.socket, tmux_args)


if __name__ == "__main__":
    main()
