import json,glob,os,re,sys,collections
P=os.path.expanduser('~/.claude/projects/-Users-chudy-Library-Application-Support-Kodi-addons-plugin-video-milionar/')
ROOT='/Users/chudy/Library/Application Support/Kodi/addons/plugin.video.milionar/'
# collect events with timestamps
events=[]   # (ts, order, kind, payload)
results={}  # tool_use_id -> text
uses={}
n=0
for f in glob.glob(P+'*.jsonl'):
    for line in open(f,encoding='utf-8',errors='ignore'):
        try: d=json.loads(line)
        except: continue
        ts=d.get('timestamp') or ''
        m=d.get('message') or {}
        c=m.get('content')
        if not isinstance(c,list): continue
        for b in c:
            t=b.get('type')
            if t=='tool_use':
                uses[b['id']]=(ts,b['name'],b.get('input',{}))
            elif t=='tool_result':
                cont=b.get('content')
                if isinstance(cont,list):
                    cont=''.join(x.get('text','') for x in cont if isinstance(x,dict))
                results[b.get('tool_use_id')]=cont if isinstance(cont,str) else ''
seq=sorted(((ts,i,name,inp) for i,(ts,name,inp) in uses.items()),key=lambda x:(x[0],x[1]))
print('tool uses',len(seq),file=sys.stderr)
vfs={}; src={}; stale=collections.Counter(); last={}
def strip_cat(text):
    out=[]
    for ln in text.split('\n'):
        m=re.match(r'^\s*(\d+)\t(.*)$',ln)
        if m: out.append(m.group(2))
        else:
            if re.match(r'^\s*(\d+)$',ln): out.append('')
            else: return None
    return '\n'.join(out)
for ts,i,name,inp in seq:
    fp=inp.get('file_path')
    if not fp or not fp.startswith(ROOT): continue
    rel=fp[len(ROOT):]
    if name=='Write':
        vfs[rel]=inp.get('content',''); src[rel]='write'; last[rel]=ts
    elif name=='Edit':
        old,new=inp.get('old_string',''),inp.get('new_string','')
        if rel in vfs:
            if old in vfs[rel]:
                vfs[rel]=vfs[rel].replace(old,new) if inp.get('replace_all') else vfs[rel].replace(old,new,1); src[rel]=src.get(rel,'')+'+edit'; last[rel]=ts
            else: stale[rel]+=1
        else: stale[rel]+=1
    elif name=='Read':
        if inp.get('offset') or inp.get('limit') or inp.get('pages'): 
            # partial read: only usable if it starts at line 1
            pass
        res=results.get(i)
        if not res or res.startswith('Error') : continue
        txt=strip_cat(res.split('\n\n<system-reminder>')[0].rstrip('\n'))
        if txt is None: continue
        full = not inp.get('offset') and not inp.get('limit')
        if full or rel not in vfs:
            if full or (not inp.get('offset')):
                vfs[rel]=txt; src[rel]='read'+('' if full else '-partial'); last[rel]=ts
import pickle
pickle.dump((vfs,src,dict(stale),last),open(sys.argv[1],'wb'))
print('files',len(vfs),'stale-edits',sum(stale.values()),file=sys.stderr)
