import py7zr, os, subprocess, sys, glob

MUN = "220700"  # Oeiras - PI

def run(arc):
    base = arc.replace('.7z','')
    txt = base + '.txt'
    if not os.path.exists(txt):
        with py7zr.SevenZipFile(arc,'r') as z:
            names = [f.filename for f in z.list()]
            z.extract(path='.', targets=names)
        # normalize name
        for n in names:
            if n != txt and n.upper().endswith('.TXT'):
                os.rename(n, txt)
    out = 'oeiras_' + base + '.csv'
    with open(txt, 'r', encoding='latin-1', errors='replace') as fi, open(out,'w',encoding='utf-8') as fo:
        hdr = fi.readline()
        fo.write(hdr)
        n=0
        for line in fi:
            p = line.split(';')
            if len(p) > 4 and p[3] == MUN:
                fo.write(line); n+=1
    os.remove(txt)
    print(f"{base}: {n} linhas Oeiras", flush=True)

for arc in sorted(glob.glob('CAGED*2026*.7z')):
    run(arc)
