"""Import old replay ledger events into the activity database once per file hash."""
import argparse
import hashlib
import json
from pathlib import Path
import re
from activity_privacy import clean
from gauntlet import Store,utc

def import_file(store,path):
    raw=path.read_bytes();key='ledger_import:'+hashlib.sha256(raw).hexdigest()
    data=json.loads(raw);match=re.fullmatch(r'attempt_(\d+)_year_(\d+)\.json',path.name)
    if not match:raise ValueError('Unexpected ledger filename')
    attempt,year=map(int,match.groups());rows=data.get('events')
    if not isinstance(rows,list):raise ValueError('Missing ledger events')
    with store.lock,store.connect() as db:
        if db.execute('SELECT 1 FROM metadata WHERE key=?',(key,)).fetchone():return 0
        # A live-instrumented year already has its events; avoid replaying duplicates.
        if db.execute("SELECT 1 FROM events WHERE kind LIKE 'REPLAY_%' AND json_extract(payload,'$.attempt')=? AND json_extract(payload,'$.calendar_year')=? LIMIT 1",(attempt,year)).fetchone():return 0
        for row in rows:
            payload=clean({'attempt':attempt,'calendar_year':year,'activity':row,'origin':'IMPORTED_ARCHIVED_LEDGER','source_file':path.name})
            db.execute('INSERT INTO events(created_at,kind,payload) VALUES(?,?,?)',(utc(),'ARCHIVED_'+str(row.get('type','EVENT')),json.dumps(payload)))
        db.execute('INSERT INTO metadata(key,value) VALUES(?,?)',(key,path.name))
    return len(rows)

if __name__=='__main__':
    p=argparse.ArgumentParser(description=__doc__);p.add_argument('--db',type=Path,required=True);p.add_argument('--ledgers',type=Path,required=True);a=p.parse_args();store=Store(a.db)
    print(json.dumps({'imported_events':sum(import_file(store,f) for f in sorted(a.ledgers.glob('attempt_*_year_*.json')))}))
