# BEGIN CHANGE: force messages.ts to valid UTF-8
from pathlib import Path

path = Path(r"p:\OT\OTSERVER\pedro\html\portal\src\i18n\messages.ts")
raw = path.read_bytes()
try:
    text = raw.decode("utf-8")
    print("already utf-8")
except UnicodeDecodeError as e:
    print("fixing from latin-1, err at", e.start)
    text = raw.decode("latin-1")

# ensure guild key present in shop locales (idempotent)
needles = [
    (
        '        not_enough_points: "Premium Points insuficientes.",\n\n        buy_failed: "Falha na compra.",',
        '        not_enough_points: "Premium Points insuficientes.",\n\n'
        '        not_enough_guild_points: "Guild Points insuficientes.",\n\n'
        '        buy_failed: "Falha na compra.",',
    ),
    (
        '        not_enough_points: "Not enough Premium Points.",\n\n        buy_failed: "Purchase failed.",',
        '        not_enough_points: "Not enough Premium Points.",\n\n'
        '        not_enough_guild_points: "Not enough Guild Points.",\n\n'
        '        buy_failed: "Purchase failed.",',
    ),
    (
        '        not_enough_points: "Premium Points insuficientes.",\n\n        buy_failed: "Fallo en la compra.",',
        '        not_enough_points: "Premium Points insuficientes.",\n\n'
        '        not_enough_guild_points: "Guild Points insuficientes.",\n\n'
        '        buy_failed: "Fallo en la compra.",',
    ),
]

# Only apply shop inserts when target_account context - safer done via count of guild key
if text.count("not_enough_guild_points") < 4:
    # type
    t_old = "      not_enough_points: string;\n\n      buy_failed: string;"
    t_new = (
        "      not_enough_points: string;\n\n"
        "      not_enough_guild_points: string;\n\n"
        "      buy_failed: string;"
    )
    if "not_enough_guild_points: string" not in text and t_old in text:
        text = text.replace(t_old, t_new, 1)
    for old, new in needles:
        if new.split("not_enough_guild_points")[1][:20] in text and old not in text:
            continue
        if old in text and "not_enough_guild_points" not in text[text.find(old) : text.find(old) + len(old) + 80]:
            text = text.replace(old, new, 1)

out = text.encode("utf-8")
out.decode("utf-8")
path.write_bytes(out)
print("written", len(out), "guild keys", text.count("not_enough_guild_points"))
# END CHANGE
