"""Refaz as contagens publicadas pela LCF em 6/11/2026, sem bibliotecas externas.

Baixe o JSON desta reportagem e execute:
  python reproduzir-enem-letras.py enem-letra-campea.json

O JSON contém a transcrição e o link de cada gabarito oficial utilizado.
O programa recalcula a partir de cada resposta; não usa os totais publicados.
Não calcula TRI, não usa dados pessoais, não prevê 2026.
"""
import json, sys
from collections import Counter
from pathlib import Path

def calculate(data):
    books={b['year']:b for b in data['booklets']}
    letters='ABCDE'
    ranges={'LC':(6,45),'CH':(46,90)}
    def counts(year,area):
        low,high=ranges[area]
        return Counter(r['answer'] for r in books[year]['records'] if low<=r['question']<=high)
    def best(c):return sorted(letters,key=lambda l:(-c[l],l))[0]
    result={r:{'hits':0,'valid':0,'blocks':0} for r in ['fixa_c','campea_anterior','campea_historica','melhor_depois']}
    rows=[]
    for year in range(2018,2025):
        for area in ranges:
            target=counts(year,area)
            accumulated=Counter()
            for past in range(2017,year):accumulated.update(counts(past,area))
            chosen={'fixa_c':'C','campea_anterior':best(counts(year-1,area)),'campea_historica':best(accumulated),'melhor_depois':best(target)}
            for rule,letter in chosen.items():
                row={'year':year,'area':area,'rule':rule,'letter':letter,'hits':target[letter],'valid':sum(target.values())}
                rows.append(row)
                result[rule]['hits']+=row['hits'];result[rule]['valid']+=row['valid'];result[rule]['blocks']+=1
    return result,rows

if __name__=='__main__':
    source=Path(sys.argv[1] if len(sys.argv)>1 else 'enem-letra-campea.json')
    data=json.loads(source.read_text(encoding='utf-8'))
    result,rows=calculate(data)
    for rule,r in result.items():print(f"{rule}: {r['hits']}/{r['valid']} = {100*r['hits']/r['valid']:.6f}% ({r['blocks']} blocos)")
