#!/usr/bin/env python3
"""
Re-apply OpenClaw reasoning spoiler patch after updates.
Applies: patches/openclaw-reasoning-spoiler.patch

Run after every `openclaw update`:
  python3 scripts/patch-reasoning-format.py && openclaw gateway restart

Requested by Zach, implemented 2026-02-24.
"""

import subprocess, sys, os

DIST = "/home/linuxbrew/.linuxbrew/lib/node_modules/openclaw/dist"
PATCH = os.path.join(os.path.dirname(__file__), "../patches/openclaw-reasoning-spoiler.patch")
PATCH = os.path.abspath(PATCH)

# First try patch-based apply
result = subprocess.run(
    ["patch", "--dry-run", "-p0", "-d", DIST, "-i", PATCH],
    capture_output=True, text=True
)

if result.returncode == 0:
    apply = subprocess.run(
        ["patch", "-p0", "-d", DIST, "-i", PATCH],
        capture_output=True, text=True
    )
    print(apply.stdout)
    if apply.returncode == 0:
        print("✅ Patch applied successfully via patch file.")
        print("Restart gateway: openclaw gateway restart")
        sys.exit(0)
    else:
        print("❌ Patch failed:", apply.stderr)
else:
    print("⚠️  patch --dry-run failed (file may have changed after update). Falling back to string replace...")

# Fallback: string replace
files = [
    f"{DIST}/image-_0vi_hl_.js",
    f"{DIST}/image-Bd603NuE.js",
    f"{DIST}/image-Cl4RgYGS.js",
    f"{DIST}/image-Dv8Df3t9.js",
]

old = r'return `Reasoning:\n${trimmed.split("\n").map((line) => line ? `_${line}_` : line).join("\n")}`;'
new = r'return `---\n||${trimmed.split("\n").map((line) => line ? `*${line}*` : line).join("\n")}||\n---`;'

patched = 0
for path in files:
    try:
        with open(path) as f:
            content = f.read()
        if old in content:
            with open(path, "w") as f:
                f.write(content.replace(old, new))
            print(f"✅ Patched: {path}")
            patched += 1
        elif new in content:
            print(f"⏭️  Already patched: {path}")
        else:
            print(f"⚠️  Pattern not found (update changed the file): {path}")
    except FileNotFoundError:
        print(f"❌ Not found: {path}")

if patched:
    print(f"\n✅ {patched} file(s) patched. Run: openclaw gateway restart")
else:
    print("\n⚠️  Nothing patched — pattern may have moved. Manual update needed.")
