#!/usr/bin/env python3
"""Troca o banner do console por MAVERICK mantendo exatamente 223 caracteres.

    python patch_banner.py --dry-run
    python patch_banner.py --apply

Alvo: patched/Maverick.exe (e replica em text/mirror_systemruntime/Maverick/).
Reescreve o item do heap #US in-place; comprimento idêntico = metadata intacta.
"""
import argparse
import shutil
import sys
from pathlib import Path

import dnfile

SRC = Path(r"C:\Users\Admin\Links\historia-index\patched\Maverick.exe")
MIRROR = Path(r"C:\Users\Admin\Links\historia-index\text\mirror_systemruntime\Maverick\Maverick.exe")
ORIG_TOTAL = 223

ART = [
    " __  __    _    __   __ _____ ____  ___ _  _",
    "|  \\/  |  / \\   \\ \\ / /| ____|  _ \\|_ _| |/",
    "| |\\/| | / _ \\   \\ V / |  _| | |_) || || ' /",
    "| |  | |/ ___ \\   | |  | |___|  _ < | || . \\",
    "|_|  |_/_/   \\_\\  |_|  |_____|_| \\_\\___|_|\\_",
]


def build_banner(total=ORIG_TOTAL):
    """Monta 5 linhas + 4 separadores de 1 char = total exato."""
    body = len("".join(ART))
    seps = total - body
    if seps < 4:
        raise SystemExit(f"arte tem {body} chars; não fecha {total}")
    # distribui os bytes de separador como '\n' entre as linhas + padding final
    parts = []
    remaining = seps
    for i, line in enumerate(ART):
        parts.append(line)
        if i < len(ART) - 1:
            parts.append("\n")
            remaining -= 1
    text = "".join(parts) + " " * remaining
    if len(text) != total:
        raise SystemExit(f"gerado {len(text)}, esperado {total}")
    return text


def heap_slice(pe, data):
    us = pe.net.user_strings
    off = us.file_offset
    return off, us.sizeof(), data[off : off + us.sizeof()]


def locate(raw):
    """Devolve (pos_do_lenbyte, pos_do_conteudo, texto_atual)."""
    i = raw.find(bytes("| __ )", "utf-16le"))
    if i < 0:
        return None
    for pos in range(max(0, i - 900), i):
        ln = raw[pos]
        if 30 <= ln <= 250:
            end = pos + 1 + ln * 2
            if end > len(raw):
                continue
            try:
                text = raw[pos + 1 : end].decode("utf-16le")
            except Exception:
                continue
            if "| __ )" in text and "____" in text:
                return pos, pos + 1, text
    return None


def safe_write(path: Path, blob: bytes):
    """Grava via arquivo temporário + replace, para não travar em handle aberto."""
    tmp = path.with_suffix(path.suffix + ".tmp")
    with open(tmp, "wb") as f:
        f.write(blob)
    try:
        path.unlink()
    except FileNotFoundError:
        pass
    tmp.replace(path)


def main():
    try:
        sys.stdout.reconfigure(encoding="utf-8", errors="replace")
    except AttributeError:
        pass
    ap = argparse.ArgumentParser()
    ap.add_argument("--apply", action="store_true")
    args = ap.parse_args()

    if not SRC.exists():
        sys.exit(f"fonte ausente: {SRC}")

    new_banner = build_banner()
    print(f"banner novo: {len(new_banner)} chars")
    for line in new_banner.split("\n"):
        print(f"  |{line}|")

    data = SRC.read_bytes()
    pe = dnfile.dnPE(str(SRC))
    off, size, raw = heap_slice(pe, data)
    hit = locate(raw)
    if hit is None:
        sys.exit("banner não localizado no heap #US")
    len_pos, content_pos, old_banner = hit
    abs_len = off + len_pos
    abs_content = off + content_pos
    print(f"\nlocalizado: lenbyte@0x{abs_len:x} conteúdo@0x{abs_content:x} ({len(old_banner)} chars)")
    print(f"antigo: {old_banner.splitlines()[0][:60]}...")

    if len(old_banner) != len(new_banner):
        sys.exit(f"tamanho diverge: {len(old_banner)} != {len(new_banner)}")

    if not args.apply:
        print("\n(dry-run) use --apply")
        return

    encoded = new_banner.encode("utf-16le")
    patched = bytearray(data)
    patched[abs_content : abs_content + len(encoded)] = encoded

    safe_write(SRC, bytes(patched))
    print(f"gravado {SRC.name}")

    MIRROR.parent.mkdir(parents=True, exist_ok=True)
    shutil.copy2(SRC, MIRROR)
    print(f"replicado em {MIRROR}")

    verify = dnfile.dnPE(str(SRC))
    check = verify.net.mdtables.Assembly.rows[0].Name
    print(f"verificação: assembly={check} tipos={len(verify.net.mdtables.TypeDef.rows)}")


if __name__ == "__main__":
    main()
