#!/usr/bin/env bash
# Собрать GOG/Whisky логи за N часов (по умолчанию 7) + timeline событий.
set -euo pipefail
GOG_DIR="$(cd "$(dirname "$0")" && pwd)"
# shellcheck source=config.sh
source "${GOG_DIR}/config.sh"

HOURS="${1:-7}"
OUT="${2:-${HOME}/code/local_machine/temp/gog-logs-${HOURS}h-$(date +%Y%m%d-%H%M%S)}"
GALOG="${BOTTLE_DIR}/drive_c/ProgramData/GOG.com/Galaxy/logs"
mkdir -p "${OUT}"

cp -R "${GALOG}" "${OUT}/galaxy-logs" 2>/dev/null || true
mkdir -p "${OUT}/whisky-logs"
cp "${HOME}/Library/Logs/com.franke.Whisky"/*.log "${OUT}/whisky-logs/" 2>/dev/null || true
[[ -f "/tmp/gog-galaxy-client-${BOTTLE_NAME}.log" ]] && cp "/tmp/gog-galaxy-client-${BOTTLE_NAME}.log" "${OUT}/" || true

df -h "$(gog_data_volume_path)" >"${OUT}/disk.txt"
pgrep -fl 'Galaxy|GOG|explorer.*GOG' >"${OUT}/processes-now.txt" 2>/dev/null || echo "(none)" >"${OUT}/processes-now.txt"
plutil -p "${BOTTLE_DIR}/Metadata.plist" >"${OUT}/metadata.plist.txt" 2>/dev/null || true
[[ -f "${BOTTLE_DIR}/Program Settings/GalaxyClient.exe.plist" ]] && \
  plutil -p "${BOTTLE_DIR}/Program Settings/GalaxyClient.exe.plist" >"${OUT}/GalaxyClient.exe.plist.txt"

python3 <<PY
import re
from datetime import datetime, timedelta
from pathlib import Path

hours = int("${HOURS}")
out = Path("${OUT}")
cutoff = datetime.now() - timedelta(hours=hours)
pat = re.compile(r"^(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.\d{3})")
keys = (
    "will continue", "will exit", "Second client", "Showing login", "foreground",
    "Deelevate", "Fatal", "deelevated", "Reloaded without", "Command-line parameters",
    "parent window", "eglInitialize",
)
logdir = Path("${GALOG}")
lines = [f"# GOG Galaxy timeline (last {hours}h)\n", f"cutoff_local={cutoff.isoformat()}\n", f"bottle={Path('${BOTTLE_DIR}').name}\n\n"]
for fn in sorted(logdir.glob("*.log")):
    lines.append(f"## {fn.name}\n")
    for line in fn.read_text(errors="replace").splitlines():
        m = pat.match(line)
        if not m:
            continue
        try:
            ts = datetime.strptime(m.group(1), "%Y-%m-%d %H:%M:%S.%f")
        except ValueError:
            continue
        if ts < cutoff:
            continue
        if any(k.lower() in line.lower() for k in keys):
            lines.append(line[:600] + "\n")
    lines.append("\n")
(out / "timeline.md").write_text("".join(lines), encoding="utf-8")
PY

cat >"${OUT}/README.txt" <<EOF
GOG log bundle (${HOURS}h)
Generated: $(date)
Bottle: ${BOTTLE_NAME} (${BOTTLE_ID})

Read first: timeline.md
Galaxy logs: galaxy-logs/
Whisky: whisky-logs/
EOF

echo "OK: ${OUT}"
echo "  timeline.md — события за ${HOURS}ч"
ls -la "${OUT}"
