#!/usr/bin/env python3
"""Repair messages.ts: keep valid UTF-8 multibyte; upgrade stray Latin-1 bytes."""
from pathlib import Path

path = Path(r"P:/OT/OTSERVER/pedro/html/portal/src/i18n/messages.ts")
data = path.read_bytes()
out = bytearray()
i = 0
n = len(data)
fixed = 0
while i < n:
    matched = False
    for length in (4, 3, 2, 1):
        if i + length > n:
            continue
        chunk = data[i : i + length]
        try:
            chunk.decode("utf-8")
        except UnicodeDecodeError:
            continue
        out.extend(chunk)
        i += length
        matched = True
        break
    if not matched:
        ch = data[i : i + 1].decode("latin-1")
        out.extend(ch.encode("utf-8"))
        fixed += 1
        i += 1

text = out.decode("utf-8")
path.write_text(text, encoding="utf-8", newline="\n")
print(f"fixed_latin1_bytes={fixed} size={len(out)}")
