"""Le os valores de verdade de um .safetensors e procura corrupcao.

Diferente de so listar chaves: aqui os dados SAO lidos e NaN / inf / |max| > 1000
sao reportados. Le no maximo MAXLIN linhas por grupo de chaves, entao o pico de
RAM fica baixo mesmo em arquivos de 34 GB.

uso:
  python -s check_safetensors.py ARQUIVO [ARQUIVO ...]
  python -s check_safetensors.py --pasta PASTA        (varre todos os .safetensors)
"""

import os
import re
import sys
import glob

import torch
from safetensors import safe_open

PADRAO = r"adaln|t_table|t_emb|basis|time_embed|mean|norm"
MAXLIN = 512
LIMITE = 1000.0


def abre(path):
    try:
        return safe_open(path, framework="pt", device="cpu")
    except Exception:
        return safe_open(path, "pt")


def analisa(path):
    print("=" * 78)
    print("ARQUIVO:", path)
    if not os.path.exists(path):
        print("   ### NAO EXISTE")
        return 1
    tam = os.path.getsize(path)
    print("   bytes: %d  (%.2f GB)" % (tam, tam / 1024.0 ** 3))

    problemas = 0
    with abre(path) as f:
        print("   metadata:", f.metadata())
        ks = list(f.keys())
        print("   tensores:", len(ks))

        grupos = {}
        for k in ks:
            if re.search(PADRAO, k, re.I):
                grupos.setdefault(re.sub(r"\d+", "#", k), []).append(k)

        print("   --- chaves que casam com /%s/ ---" % PADRAO)
        if not grupos:
            print("      (nenhuma)")
        for g in sorted(grupos):
            try:
                sl = f.get_slice(grupos[g][0])
                print("      %4dx %-50s %-14s %s"
                      % (len(grupos[g]), g[:50], str(list(sl.get_shape())), sl.get_dtype()))
            except Exception as e:
                print("      %4dx %-50s (erro: %s)" % (len(grupos[g]), g[:50], e))

        print("   --- CHECK DE VALORES (ate %d linhas por grupo) ---" % MAXLIN)
        if not grupos:
            print("      (nada a checar)")
        for g in sorted(grupos):
            k = grupos[g][0]
            try:
                sl = f.get_slice(k)
                sh = list(sl.get_shape())
                if len(sh) > 1:
                    t = sl[:min(sh[0], MAXLIN)].to(torch.float32)
                else:
                    t = sl[:].to(torch.float32)
            except Exception:
                # alguns backends nao deixam fatiar o slice; cai no tensor inteiro
                try:
                    t = f.get_tensor(k)
                    if t.ndim > 1:
                        t = t[:min(t.shape[0], MAXLIN)]
                    t = t.to(torch.float32)
                except Exception as e:
                    print("      %-50s ERRO ao ler: %s" % (g[:50], e))
                    problemas += 1
                    continue

            nan = int(torch.isnan(t).sum())
            inf = int(torch.isinf(t).sum())
            fin = t[torch.isfinite(t)]
            if fin.numel() == 0:
                print("      %-50s *** TODOS NAO-FINITOS ***" % g[:50])
                problemas += 1
                continue

            mx = float(fin.abs().max())
            marca = ""
            if nan:
                marca += "  NaN=%d" % nan
            if inf:
                marca += "  inf=%d" % inf
            if mx > LIMITE:
                marca += "  *** |max|>%.0f ***" % LIMITE
            if marca:
                problemas += 1

            print("      %-50s n=%-8d min=%+.5f max=%+.5f mean=%+.5f std=%.6f%s"
                  % (g[:50], t.numel(), float(fin.min()), float(fin.max()),
                     float(fin.mean()), float(fin.std()), marca))

    print("   >>> PROBLEMAS NESTE ARQUIVO: %d" % problemas)
    return problemas


def main(argv):
    alvos = []
    if argv and argv[0] == "--pasta":
        for pasta in argv[1:]:
            alvos += sorted(glob.glob(os.path.join(pasta, "*.safetensors")))
        if not alvos:
            print("### nenhum .safetensors encontrado em", argv[1:])
            return 1
    else:
        alvos = argv

    if not alvos:
        print(__doc__)
        return 1

    total = 0
    for p in alvos:
        try:
            total += analisa(p)
        except Exception as e:
            print("ERRO em", p, ":", e)
            total += 1

    print()
    print("########## TOTAL DE PROBLEMAS: %d ##########" % total)
    return 0


if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))
