#!/usr/bin/python3
import contextlib
import json
import os
import re
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


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)
