"""Agrupa as divergencias de uma rodada (alvo x base) pela causa: mensagem de erro + arquivo:linha.

Uso: python agrupa.py [crawl-alvo83.json]
"""
import collections
import json
import re
import sys
from pathlib import Path

from compara import classificar
from config import SAIDA

BASE = Path(r"C:\projetos\php83\logs\crawl-base74.final.json")
_LOC = re.compile(r"(?:in|em) (?:/var/www/html/accia(?:-php83)?/)?(\S+\.php)(?::| on line )(\d+)")


def causa(motivo: str) -> str:
    m = _LOC.search(motivo)
    texto = re.sub(r"^log novo: (cm_log\[\d\] )?", "", motivo)
    texto = re.sub(r"(yii\\+base\\+)?ErrorException(:\d+)?: ", "", texto)
    texto = _LOC.sub("", texto).strip(" :")[:160]
    return (f"{m.group(1)}:{m.group(2)} | " if m else "") + texto


def main():
    alvo = Path(sys.argv[1]) if len(sys.argv) > 1 else SAIDA / "crawl-alvo83.json"
    base = {r["url"]: r for r in json.loads(BASE.read_text(encoding="utf8"))["registros"]}
    regs = json.loads(alvo.read_text(encoding="utf8"))["registros"]
    grupos = collections.defaultdict(list)
    for r in regs:
        c = classificar(base[r["url"]], r)
        if c["veredito"] != "igual":
            motivo = next((l for l in r["log_novos"] if "Exception" in l or "Error" in l or "Warning" in l
                           or "Deprecated" in l), c["motivos"][0])
            grupos[causa(motivo)].append(f"{base[r['url']]['status']}->{r['status']} {r['url']}")
    print(f"{len(regs)} URLs, {sum(len(v) for v in grupos.values())} divergentes, {len(grupos)} causas")
    for k, v in sorted(grupos.items(), key=lambda kv: -len(kv[1])):
        print(f"\n[{len(v)}] {k}")
        for u in v[:3]:
            print("     ", u[:150])


if __name__ == "__main__":
    main()
