import subprocess,json,os,sys,time
from pathlib import Path
ACCOUNT='friday.uplink@gmail.com'
folders={
 '/home/agent/family/Lernen/Französisch/Francine_Oesch_Email_Anhaenge/PDFs':'1Aj-NYZ_MCDvaQA3dJAYVQsQONh3l-Yfp',
 '/home/agent/family/Lernen/Französisch/Francine_Oesch_Email_Anhaenge/Weitere_Anhaenge_DOCX':'1Y10ttAGZbtp0VPyZrqZ_MwoGg9ogHmOw',
 '/home/agent/family/Lernen/Französisch/Francine_Oesch_Email_Anhaenge/Weitere_Anhaenge_Sonstige':'1QOoKGQhJ0jNYYS5yCbHdv_jF6SIG68DM',
 '/home/agent/family/Lernen/Französisch/Francine_Oesch_Email_Anhaenge':'1NtKbso7vvxU1W5Ral4-BLmQ_itVt2aL3',
}
env={**os.environ,'HOME':'/home/agent','XDG_CONFIG_HOME':'/home/agent/.config','GOG_KEYRING_PASSWORD':'LammBitch30'}
def run(args, timeout=180, check=True):
    p=subprocess.run(args, env=env, text=True, capture_output=True, timeout=timeout)
    if check and p.returncode:
        raise RuntimeError((p.stderr or p.stdout)[:1000])
    return p

def children_names(fid):
    p=run(['gog','-a',ACCOUNT,'drive','search',f"'{fid}' in parents and trashed = false",'--max','1000','--json','--results-only','--no-input'], timeout=180)
    return {x.get('name') for x in json.loads(p.stdout or '[]')}

uploaded=0; skipped=0; failed=[]
for local_dir, fid in folders.items():
    d=Path(local_dir)
    files=[p for p in sorted(d.iterdir()) if p.is_file()]
    existing=children_names(fid)
    for path in files:
        if path.name in existing:
            skipped += 1; continue
        ok=False; last=''
        for attempt in range(1,4):
            p=run(['gog','-a',ACCOUNT,'drive','upload',str(path),'--parent',fid,'--json','--no-input'], timeout=240, check=False)
            if p.returncode==0:
                uploaded += 1; ok=True; existing.add(path.name)
                if uploaded % 25 == 0: print(f'uploaded={uploaded} skipped={skipped}', flush=True)
                break
            last=(p.stderr or p.stdout)[:500]
            time.sleep(5*attempt)
        if not ok:
            failed.append({'path':str(path),'error':last})
            print('FAILED', path, last[:120], file=sys.stderr, flush=True)
print(json.dumps({'uploaded':uploaded,'skipped':skipped,'failed':len(failed),'failed_items':failed[:20]}, ensure_ascii=False, indent=2))
if failed:
    Path('/home/agent/tmp/franzoesisch_import/resume_upload_failed.json').write_text(json.dumps(failed,ensure_ascii=False,indent=2),encoding='utf-8')
    sys.exit(2)
