#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Patch AnimFX.lua + UI.lua:
 1. DeathCinematic: remove ScreenBlackout, Vignette, CinematicBars, BellTolls, BloodFlash
 2. UI ShowBook: remove CandleFlicker lines
 3. UI outroAnim: remove CinematicBars(false) call
 4. Fix all garbled double-encoded UTF-8 chars in UI.lua
"""
import re

BASE = r"C:\Users\Norme\Documents\verdent-projects\new-project\GuildDeathLog"

# ─── 1. ANIMFX.LUA ────────────────────────────────────────────────────────────
anim_path = BASE + r"\Modules\AnimFX.lua"
with open(anim_path, 'r', encoding='utf-8') as f:
    anim = f.read()

# Replace the first 4 blocks of DeathCinematic (Blackout/Vignette/BellTolls/BloodFlash)
OLD_DEATH_HEAD = (
    "    r, g, b = r or 0.80, g or 0.10, b or 0.10\n"
    "\n"
    "    -- \u2605 t=0.00 \u2014 DUNKELHEIT & VIGNETTE\n"
    "    AnimFX.ScreenBlackout(0.28, 0.72, 0.14)\n"
    "    AnimFX.Vignette(3.4, 0.80)\n"
    "\n"
    "    -- \u2605 t=0.05 \u2014 GLOCKE + KLASSEN-FLASH + Wei\u00dfer HORROR-CUT\n"
    "    C_Timer.After(0.05, function()\n"
    "        AnimFX.BellTolls(r, g, b)\n"
    "    end)\n"
    "\n"
    "    -- \u2605 t=0.30 \u2014 BLUTROTER FLASH (Schockmoment)\n"
    "    C_Timer.After(0.30, function()\n"
    "        AnimFX.ScreenFlash(0.68, 0.0, 0.0, 0.55, 0.48)\n"
    "    end)\n"
)

NEW_DEATH_HEAD = (
    "    r, g, b = r or 0.80, g or 0.10, b or 0.10\n"
    "\n"
    "    -- ★ t=0.05 — KLASSEN-FLASH + SOUND (kein Blackout/Vignette)\n"
    "    C_Timer.After(0.05, function()\n"
    "        AnimFX.ScreenFlash(r * 0.40, g * 0.06, b * 0.03, 1.0, 0.55)\n"
    "        C_Timer.After(0.16, function()\n"
    "            AnimFX.ScreenFlash(0.88, 0.84, 0.74, 0.20, 0.75)\n"
    "        end)\n"
    "        C_Timer.After(0.05, function() pcall(function() PlaySound(878) end) end)\n"
    "        C_Timer.After(0.88, function() pcall(function() PlaySound(878) end) end)\n"
    "    end)\n"
    "\n"
)

if OLD_DEATH_HEAD in anim:
    anim = anim.replace(OLD_DEATH_HEAD, NEW_DEATH_HEAD)
    print("AnimFX: DeathCinematic head patched")
else:
    print("AnimFX: WARNING - DeathCinematic head not found, trying line-based patch")
    # Fallback: replace lines 1138-1150 directly
    lines = anim.splitlines(keepends=True)
    # find function start
    start = None
    for i, l in enumerate(lines):
        if "function AnimFX.DeathCinematic" in l:
            start = i; break
    if start:
        # find the end of the old BellTolls + BloodFlash block (look for t=0.44)
        end = start
        for i in range(start, min(start+30, len(lines))):
            if "t=0.44" in lines[i]:
                end = i; break
        NEW_LINES = [
            lines[start],  # function header
            '    r, g, b = r or 0.80, g or 0.10, b or 0.10\n',
            '\n',
            '    -- ★ t=0.05 — KLASSEN-FLASH + SOUND (kein Blackout/Vignette)\n',
            '    C_Timer.After(0.05, function()\n',
            '        AnimFX.ScreenFlash(r * 0.40, g * 0.06, b * 0.03, 1.0, 0.55)\n',
            '        C_Timer.After(0.16, function()\n',
            '            AnimFX.ScreenFlash(0.88, 0.84, 0.74, 0.20, 0.75)\n',
            '        end)\n',
            '        C_Timer.After(0.05, function() pcall(function() PlaySound(878) end) end)\n',
            '        C_Timer.After(0.88, function() pcall(function() PlaySound(878) end) end)\n',
            '    end)\n',
            '\n',
        ]
        lines = lines[:start] + NEW_LINES + lines[end:]
        anim = "".join(lines)
        print("AnimFX: DeathCinematic head patched via line-based fallback")

# Also remove the "t=0.44" comment line's extra blank line before it if any
# (minor cleanup only)

with open(anim_path, 'w', encoding='utf-8') as f:
    f.write(anim)
print("AnimFX.lua saved")

# ─── 2. UI.LUA ────────────────────────────────────────────────────────────────
ui_path = BASE + r"\Modules\UI.lua"
with open(ui_path, 'r', encoding='utf-8') as f:
    ui = f.read()

changes = 0

# 2a. Remove CandleFlicker lines from ShowBook
# Lines like:  self._candle1 = FX.CandleFlicker(f, -390, 0, ...)
#              self._candle2 = FX.CandleFlicker(f,  390, 0, ...)
# and their stop counterparts
for pat in [
    r"[ \t]*self\._candle1 = FX\.CandleFlicker\([^\n]*\)\n",
    r"[ \t]*self\._candle2 = FX\.CandleFlicker\([^\n]*\)\n",
    r"[ \t]*if self\._candle1[^\n]*\n",
    r"[ \t]*if self\._candle2[^\n]*\n",
]:
    new_ui, n = re.subn(pat, "", ui)
    if n > 0:
        ui = new_ui
        changes += n
        print(f"UI: Removed {n}x CandleFlicker pattern: {pat[:50]}")

# 2b. Remove CinematicBars(false) from outroAnim OnFinished
for pat in [
    r"[ \t]*FX2\.CinematicBars\(false[^\n]*\)\n",
    r"[ \t]*FX\.CinematicBars\(false[^\n]*\)\n",
    r"[ \t]*local FX[23]? = GDL:GetModule\(\"AnimFX\"\)\n[ \t]*if FX[23]? then\n[ \t]*FX[23]?\.StopOverlayAmbience\([^\n]*\)\n[ \t]*FX[23]?\.CinematicBars\(false[^\n]*\)\n[ \t]*end\n",
]:
    new_ui, n = re.subn(pat, "", ui)
    if n > 0:
        ui = new_ui
        changes += n
        print(f"UI: Removed {n}x CinematicBars(false) pattern")

# Simpler targeted fix for the outroAnim block
old_outro = (
    "                local FX2 = GDL:GetModule(\"AnimFX\")\n"
    "                if FX2 then\n"
    "                    FX2.StopOverlayAmbience(o._ambienceHandles)\n"
    "                    FX2.CinematicBars(false, 0.55)\n"
    "                end\n"
)
new_outro = (
    "                local FX2 = GDL:GetModule(\"AnimFX\")\n"
    "                if FX2 then FX2.StopOverlayAmbience(o._ambienceHandles) end\n"
)
if old_outro in ui:
    ui = ui.replace(old_outro, new_outro)
    changes += 1
    print("UI: outroAnim CinematicBars(false) removed")

# 2c. Fix all double-encoded UTF-8 characters
# Format: (garbled_unicode, correct_unicode)
ENCODING_FIXES = [
    # en-dash U+2013 (E2 80 93) was mis-read as Win-1252 → â€" (U+00E2 + U+20AC + U+201C)
    ("\u00e2\u20ac\u201c", " - "),
    # em-dash U+2014 (E2 80 94) → â€" (U+00E2 + U+20AC + U+201D)
    ("\u00e2\u20ac\u201d", " - "),
    # → U+2192 (E2 86 92) → â†' (U+00E2 + U+2020 + U+2019)
    ("\u00e2\u2020\u2019", "->"),
    # ─ U+2500 (E2 94 80) box drawing → â"€ (U+00E2 + U+201D + U+20AC) — keep in comments, skip
    # ö U+00F6 (C3 B6) → Ã¶ (U+00C3 + U+00B6)
    ("\u00c3\u00b6", "\u00f6"),
    # ü U+00FC (C3 BC) → Ã¼ (U+00C3 + U+00BC)
    ("\u00c3\u00bc", "\u00fc"),
    # ä U+00E4 (C3 A4) → Ã¤ (U+00C3 + U+00A4)
    ("\u00c3\u00a4", "\u00e4"),
    # ß U+00DF (C3 9F) → ÃŸ (U+00C3 + U+0178)
    ("\u00c3\u0178", "\u00df"),
    # Ö U+00D6 (C3 96) → Ã– (U+00C3 + U+2013)
    ("\u00c3\u2013", "\u00d6"),
    # Ü U+00DC (C3 9C) → Ãœ (U+00C3 + U+0153)
    ("\u00c3\u0153", "\u00dc"),
    # Ä U+00C4 (C3 84) → Ã„ (U+00C3 + U+201E)
    ("\u00c3\u201e", "\u00c4"),
    # é U+00E9 (C3 A9) → Ã© (U+00C3 + U+00A9)
    ("\u00c3\u00a9", "\u00e9"),
    # ú U+00FA (C3 BA) → Ãº (U+00C3 + U+00BA)
    ("\u00c3\u00ba", "\u00fa"),
    # ó U+00F3 (C3 B3) → Ã³ (U+00C3 + U+00B3)
    ("\u00c3\u00b3", "\u00f3"),
]

enc_changes = 0
for old_char, new_char in ENCODING_FIXES:
    if old_char in ui:
        n = ui.count(old_char)
        ui = ui.replace(old_char, new_char)
        enc_changes += n
        print(f"UI encoding: Fixed {n}x {repr(old_char)} -> {repr(new_char)}")

if enc_changes == 0:
    print("UI encoding: No garbled chars found (already clean or different encoding)")

with open(ui_path, 'w', encoding='utf-8') as f:
    f.write(ui)
print(f"UI.lua saved ({changes} structural + {enc_changes} encoding fixes)")

# ─── 3. Also fix Milestones.lua encoding ─────────────────────────────────────
mil_path = BASE + r"\Modules\Milestones.lua"
with open(mil_path, 'r', encoding='utf-8') as f:
    mil = f.read()

mil_changes = 0
for old_char, new_char in ENCODING_FIXES:
    if old_char in mil:
        n = mil.count(old_char)
        mil = mil.replace(old_char, new_char)
        mil_changes += n
        print(f"Milestones encoding: Fixed {n}x {repr(old_char)}")

with open(mil_path, 'w', encoding='utf-8') as f:
    f.write(mil)
print(f"Milestones.lua saved ({mil_changes} encoding fixes)")

print("\nAll patches applied successfully!")
