#!/usr/bin/python3
import contextlib
import json
import os
import re
import subprocess
import sys
import tempfile
import threading
from pathlib import Path

GAME_DEBUG_CHANNELS = (
    "timestamp", "pid", "tid", "seh", "unwind", "threadname", "debugstr", "loaddll", "mscoree",
)
WINE_DEBUG_SELECTOR = re.compile(r"(?:(trace|warn|err|fixme))?([+-])([A-Za-z_][A-Za-z0-9_]*)")


def game_debug_channels(*values):
    selectors = {}
    for value in values:
        if not isinstance(value, str) or "\0" in value or len(value) > 8192:
            continue
        for part in value.split(","):
            part = part.strip()
            match = WINE_DEBUG_SELECTOR.fullmatch(part)
            if match is None:
                continue
            key = (match[1] or "", match[3])
            selectors.pop(key, None)
            selectors[key] = part
    for channel in GAME_DEBUG_CHANNELS:
        key = ("", channel)
        selectors.pop(key, None)
        selectors[key] = "+" + channel
    formatted = ",".join(selectors.values())
    if len(formatted) > 8192:
        formatted = ",".join("+" + channel for channel in GAME_DEBUG_CHANNELS)
    return formatted


def load_config():
    try:
        path = Path(os.environ.get("HOME") or "/root") / ".config/droiddeck/game-environment.json"
        with path.open(encoding="utf-8") as source:
            return json.load(source)
    except (OSError, ValueError):
        return None


def session_debug_dir(env):
    return env.get("DD_DEBUG_DIR", "")


def apply_game_debug_logs(env, config=None, debug_dir=None):
    if config is None:
        config = load_config()
    if not isinstance(config, dict) or config.get("version") != 1 or config.get("gameDebugLogs") is not True:
        return env
    if debug_dir is None:
        debug_dir = session_debug_dir(env)
    if (not isinstance(debug_dir, str) or "\0" in debug_dir or len(debug_dir) > 8192
            or not os.path.isabs(debug_dir) or not os.path.isdir(debug_dir)):
        print("droiddeck-game-env: game debug logs skipped; session log directory unavailable", file=sys.stderr)
        return env
    result = dict(env)
    result.update({
        "PROTON_LOG": "1",
        "PROTON_LOG_DIR": debug_dir,
        "PROTON_CRASH_REPORT_DIR": debug_dir,
        "DXVK_LOG_PATH": debug_dir,
        "DXVK_LOG_LEVEL": "debug",
        "VKD3D_DEBUG": "info",
        "WINEDEBUG": game_debug_channels(env.get("WINEDEBUG"), env.get("PROTON_LOG")),
    })
    return result


# Proton appends its log through one inherited descriptor and never limits it; a game that loops on an
# exception wrote 3 GB per run. Truncating keeps the first part and frees the rest, and Proton's
# appends continue from the new end.
PROTON_LOG_CAP = 64 * 1024 * 1024
PROTON_LOG_CHECK_S = 1
CAP_WATCH = r"""
import os, stat, sys, time
pid, limit, every, paths = int(sys.argv[1]), int(sys.argv[2]), float(sys.argv[3]), sys.argv[4:]
while os.path.isdir("/proc/%d" % pid):
    for path in paths:
        try:
            info = os.lstat(path)
            if stat.S_ISREG(info.st_mode) and info.st_size > limit:
                os.truncate(path, limit)
        except OSError:
            pass
    time.sleep(every)
"""


def proton_log_paths(env):
    if env.get("PROTON_LOG", "0") in ("", "0"):
        return []
    folder = env.get("PROTON_LOG_DIR") or env.get("HOME") or os.environ.get("HOME") or "/root"
    paths = [os.path.join(folder, "steam-proton.log")]
    if env.get("SteamGameId"):
        paths.insert(0, os.path.join(folder, "steam-%s.log" % env["SteamGameId"]))
    return paths


def cap_proton_log(env, pid=None, limit=PROTON_LOG_CAP, every=PROTON_LOG_CHECK_S, popen=subprocess.Popen):
    """Keep Proton's log under `limit` bytes while process `pid` (this launcher, which becomes Proton) runs."""
    paths = proton_log_paths(env)
    if not paths:
        return None
    try:
        return popen([sys.executable, "-c", CAP_WATCH, str(pid or os.getpid()), str(limit), str(every)] + paths,
                     stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
                     start_new_session=True)
    except OSError as error:
        print("droiddeck-game-env: Proton log size limit unavailable (%s)" % error, file=sys.stderr)
        return None


def capped_log(path, limit, mirror=False):
    os.makedirs(os.path.dirname(path), exist_ok=True)
    handle = open(path, "wb")
    try:
        read, write = os.pipe()
    except OSError:
        handle.close()
        raise

    def pump():
        remaining = limit
        mirror_ok = mirror
        with os.fdopen(read, "rb") as source, handle:
            while True:
                chunk = source.read1(65536)
                if not chunk:
                    break
                saved = chunk[:remaining]
                remaining -= len(saved)
                if saved:
                    try:
                        handle.write(saved)
                        handle.flush()
                    except (OSError, ValueError):
                        remaining = 0
                if mirror_ok:
                    try:
                        sys.stderr.write(chunk.decode("utf-8", "replace"))
                        sys.stderr.flush()
                    except (OSError, ValueError):
                        mirror_ok = False

    thread = threading.Thread(target=pump, daemon=True)
    thread.start()
    return write, thread


@contextlib.contextmanager
def desktop_program_logs(env):
    program = env.get("DROIDDECK_DESKTOP_PROGRAM")
    if program:
        env = dict(env)
        env.pop("DROIDDECK_DESKTOP_PROGRAM", None)
    if not program or env.get("PROTON_LOG", "0") not in ("", "0"):
        yield env, None
        return
    folder = session_debug_dir(env)
    try:
        if not os.path.isabs(folder) or not os.path.isdir(folder):
            raise OSError("session log directory unavailable")
        fd, path = tempfile.mkstemp(prefix="desktop-program-", suffix=".log", dir=folder)
        os.close(fd)
        output, thread = capped_log(path, 1024 * 1024, mirror=True)
    except OSError as error:
        print("droiddeck-game-env: desktop diagnostics unavailable (%s)" % error, file=sys.stderr)
        yield env, None
        return
    try:
        if env.get("WINEDEBUG", "-all") in ("", "-all"):
            env["WINEDEBUG"] = "-all,err+all,+mscoree,+loaddll"
        try:
            print("droiddeck-game-env: desktop program %s; first 1048576 diagnostic bytes: %s" % (program, path),
                  file=sys.stderr, flush=True)
        except OSError:
            pass
        yield env, output
    finally:
        os.close(output)
        thread.join(timeout=1)
