import py7zr, os, glob
for arc in sorted(glob.glob('CAGED*.7z')):
    base = arc[:-3]; txt = base + '.txt'; out = 'pi_' + base + '.csv'
    if os.path.exists(out): continue
    with py7zr.SevenZipFile(arc,'r') as z:
        names=[f.filename for f in z.list()]; z.extract(path='.', targets=names)
    for n in names:
        if n != txt and n.lower().endswith('.txt'): os.rename(n, txt)
    n=0
    with open(txt, encoding='utf-8', errors='replace') as fi, open(out,'w',encoding='utf-8') as fo:
        fo.write(fi.readline())
        for line in fi:
            p=line.split(';')
            if len(p)>4 and p[2]=='22':
                fo.write(line); n+=1
    os.remove(txt); print(f"{base}: {n} linhas PI", flush=True)
