"""Current-version disposable local mirror challenge; no real files or drives."""
import json, os, shutil, subprocess
from pathlib import Path
ROOT=Path(os.environ.get('PP286_WORKDIR','./pp286-work')).resolve()
ROOT.mkdir(parents=True, exist_ok=True)
TOOLS={key:Path(os.environ.get('PP286_'+key.upper()) or shutil.which(name) or name).resolve()
       for key,name in {'rsync':'rsync','rclone':'rclone','copycat':'copycat'}.items()}
rows=[]
def snapshot(path):
    return {str(p.relative_to(path)):p.read_text() for p in sorted(path.rglob('*')) if p.is_file()} if path.exists() else None
def command(tool,src,dst,attic,preview):
    if tool=='rsync':
        return [str(TOOLS[tool]),'-a','--checksum','--delete','--backup',f'--backup-dir={attic}', '--itemize-changes',*(['--dry-run'] if preview else []),str(src)+'/',str(dst)+'/']
    if tool=='rclone':
        return [str(TOOLS[tool]),'sync',str(src),str(dst),'--checksum','--backup-dir',str(attic),'--verbose',*(['--dry-run'] if preview else [])]
    return [str(TOOLS[tool]),'sync','--delete',*(['--dry-run'] if preview else []),str(src),str(dst)]
def invoke(tool,scenario,stage,src,dst,attic,preview):
    cmd=command(tool,src,dst,attic,preview)
    proc=subprocess.run(cmd,capture_output=True,text=True,timeout=20,check=False,env={**os.environ,'RCLONE_CONFIG':'/dev/null'})
    row=dict(tool=tool,scenario=scenario,stage=stage,command=cmd,exit=proc.returncode,stdout=proc.stdout,stderr=proc.stderr,dest=snapshot(dst),attic=snapshot(attic))
    rows.append(row)
    return row
for tool in TOOLS:
    base=ROOT/'challenge'/tool
    if base.exists():shutil.rmtree(base)
    src,dst,attic,rescue=(base/n for n in ('source','drive','attic','rescue'))
    src.mkdir(parents=True);dst.mkdir();attic.mkdir();rescue.mkdir()
    for n,c in {'keep.txt':'keep','changed.txt':'new','new.txt':'added'}.items():(src/n).write_text(c)
    for n,c in {'keep.txt':'keep','changed.txt':'old','removed.txt':'removed','orphan.txt':'orphan'}.items():(dst/n).write_text(c)
    os.utime(src/'changed.txt',(1640995200,1640995200));os.utime(dst/'changed.txt',(1609459200,1609459200))
    invoke(tool,'ordinary','preview',src,dst,attic,True)
    invoke(tool,'ordinary','apply',src,dst,attic,False)
    for n in ('changed.txt','removed.txt','orphan.txt'):
        if (attic/n).exists(): shutil.copy2(attic/n,rescue/n)
    rows.append(dict(tool=tool,scenario='ordinary',stage='restore',rescued=snapshot(rescue)))
    # Same size and same timestamp: only content differs.
    (src/'changed.txt').write_text('ABC');(dst/'changed.txt').write_text('XYZ')
    os.utime(src/'changed.txt',(1672531200,1672531200));os.utime(dst/'changed.txt',(1672531200,1672531200))
    invoke(tool,'equal-size-mtime','preview',src,dst,attic,True)
    invoke(tool,'equal-size-mtime','apply',src,dst,attic,False)
    # Missing source and missing drive are distinct disposable scenarios.
    shutil.rmtree(src)
    invoke(tool,'missing-source','preview',src,dst,attic,True)
    invoke(tool,'missing-source','apply',src,dst,attic,False)
    src.mkdir();(src/'present.txt').write_text('present')
    shutil.rmtree(dst)
    invoke(tool,'missing-target','preview',src,dst,attic,True)
    invoke(tool,'missing-target','apply',src,dst,attic,False)
(ROOT/'challenge.json').write_text(json.dumps(rows,indent=2)+'\n')
for r in rows:
    print(r['tool'],r['scenario'],r['stage'],'exit',r.get('exit'),'dest',r.get('dest'),'attic',r.get('attic'),'rescued',r.get('rescued'))
