"""Local disposable restic lab. Python 3.10+, stdlib only, restic 0.19.1.

Usage: python replay.py --restic /path/to/restic > receipt.json
Takes no repository, credential, restore-target, or personal-data arguments.
"""
import argparse
from datetime import datetime, timezone
import hashlib
import json
import os
from pathlib import Path
import platform
import secrets
import shutil
import sqlite3
import subprocess
import tempfile


def digest(payload):
    return hashlib.sha256(payload).hexdigest()


def manifest(root):
    return {p.relative_to(root).as_posix(): {'bytes': p.stat().st_size, 'sha256': digest(p.read_bytes())}
            for p in sorted(root.rglob('*')) if p.is_file()}


LABELS = [('images/east.pgm', 'East door'), ('images/west.pgm', 'West door')]


def originals(src):
    (src / 'images').mkdir(parents=True)
    for seed, (name, _) in enumerate(LABELS):
        (src / name).write_bytes(b'P5\n32 24\n255\n' + bytes((i*7+seed*71) % 256 for i in range(32*24)))
    (src / 'library.json').write_bytes(b'{"catalog":"catalog.sqlite3","name":"Two doors"}\n')
    with sqlite3.connect(src/'catalog.sqlite3') as conn:
        conn.execute('CREATE TABLE photo(path TEXT PRIMARY KEY, label TEXT NOT NULL, sha256 TEXT NOT NULL)')
        conn.executemany('INSERT INTO photo VALUES (?,?,?)',
                         [(name, label, digest((src/name).read_bytes())) for name,label in LABELS])
    conn.close()  # closed and committed before backup; not a live-database test


def inspect_restore(root, original):
    files = manifest(root)
    matching = sorted(n for n in original if files.get(n) == original[n])
    # Read the fixed-format PGM fixtures as images, independently of catalog availability.
    readable=[]
    for name,_ in LABELS:
        if name not in files: continue
        header=(root/name).read_bytes().split(b'\n',3)
        if len(header)==4 and header[:3]==[b'P5',b'32 24',b'255'] and len(header[3])==32*24:
            readable.append(name)
    result = {'restored_manifest':files, 'matching_files':matching,
              'missing': sorted(set(original)-set(files)), 'unexpected': sorted(set(files)-set(original)),
              'different': sorted(n for n in set(original)&set(files) if original[n] != files[n]),
              'readable_pgm_images':readable, 'catalog_rows_resolved':0}
    try:
        cfg=json.loads((root/'library.json').read_bytes())
        if cfg != {'catalog':'catalog.sqlite3', 'name':'Two doors'}: raise ValueError('unexpected library configuration')
        db=root/'catalog.sqlite3'
        if not db.is_file(): raise ValueError('catalog.sqlite3 absent; images alone have no catalog labels')
        conn=sqlite3.connect(db.resolve().as_uri()+'?mode=ro',uri=True)
        try:
            if conn.execute('PRAGMA integrity_check').fetchall() != [('ok',)]: raise ValueError('SQLite integrity check failed')
            rows=list(conn.execute('SELECT path,label,sha256 FROM photo ORDER BY path'))
            if [(p,label) for p,label,_ in rows] != LABELS: raise ValueError('expected catalog rows missing or changed')
            for p,_,expected in rows:
                if digest((root/p).read_bytes()) != expected: raise ValueError('catalog image bytes differ')
                result['catalog_rows_resolved']+=1
        finally: conn.close()
        result['catalog_check']='pass'
    except (OSError,sqlite3.Error,ValueError) as err:
        # Avoid putting temporary absolute paths or host identities in a distributed receipt.
        result['catalog_check']=str(err) if isinstance(err,ValueError) else type(err).__name__
    result['passed']=len(matching)==len(original) and not result['unexpected'] and len(readable)==2 and result['catalog_check']=='pass'
    return result


def rehearse(exe):
    exe=Path(exe).expanduser().resolve(strict=True)
    started=datetime.now(timezone.utc).isoformat()
    with tempfile.TemporaryDirectory(prefix='techfuel-restic-lab-') as tmp:
        root=Path(tmp).resolve(); src=root/'source'; clean=root/'repo-clean'; broken=root/'repo-damaged'; temp=root/'tmp'; temp.mkdir()
        env={k:v for k,v in os.environ.items() if k.upper() in ('PATH','WINDIR','SYSTEMROOT','COMSPEC','PATHEXT')}
        env.update(RESTIC_PASSWORD=secrets.token_urlsafe(32),TEMP=str(temp),TMP=str(temp),TMPDIR=str(temp))
        version=subprocess.run([str(exe),'version'],cwd=root,env=env,capture_output=True,text=True,check=True).stdout.strip()
        if not version.startswith('restic 0.19.1 '): raise SystemExit('Use restic 0.19.1 to replay this version-pinned drill.')
        original_copy=exe.read_bytes()
        events=[]

        def run(tag,repo,args,expect_ok=True):
            repo.resolve().relative_to(root)
            p=subprocess.run([str(exe),'--no-cache','-r',str(repo),*args],cwd=src,env=env,
                              text=True,encoding='utf-8',errors='replace',capture_output=True,timeout=120)
            shown=[a.replace(str(root),'<lab>') for a in args]
            events.append({'phase':tag,'repository':repo.name,'arguments':shown,'exit_code':p.returncode})
            if (p.returncode==0) != expect_ok: raise RuntimeError(f'{tag}: unexpected return {p.returncode}\n{p.stdout}\n{p.stderr}')
            return p

        def snapshot(name,args):
            p=run('backup-'+name,clean,['backup','--host','restore-lab','--tag',name,'--json',*args,'.'])
            return next(j['snapshot_id'] for j in map(json.loads,p.stdout.splitlines()) if j.get('message_type')=='summary')

        def restore(tag,repo,sid,ok):
            target=root/('restored-'+tag);target.mkdir()
            run('restore-'+tag,repo,['restore',sid,'--target',str(target)],ok)
            return inspect_restore(target,original)

        originals(src); original=manifest(src)
        if not inspect_restore(src,original)['passed']: raise RuntimeError('fixture failed its source checks')
        run('init',clean,['init','--repository-version','2'])
        good=snapshot('complete',[])
        # A valid but incomplete backup of the SAME source: deliberately exclude the application metadata.
        partial=snapshot('catalog-omitted',['--exclude','catalog.sqlite3'])
        run('structure-clean',clean,['check']);run('read-all-clean',clean,['check','--read-data'])
        ok=restore('clean',clean,good,True); missing=restore('missing-catalog',clean,partial,True)
        if not ok['passed'] or missing['passed'] or missing['missing']!=['catalog.sqlite3'] or len(missing['readable_pgm_images'])!=2 or missing['catalog_rows_resolved']:
            raise AssertionError('clean or missing-catalog control did not behave as expected')

        # Flip one encrypted byte INSIDE the east image blob in a private repository clone. Never repair/prune it.
        shutil.copytree(clean,broken)
        blob_id=original['images/east.pgm']['sha256']; located=[]
        idxs=run('locate-index',broken,['list','index']).stdout.splitlines()
        for idx in idxs:
            index=json.loads(run('read-index',broken,['cat','index',idx.strip()]).stdout)
            for pack in index['packs']:
                for blob in pack['blobs']:
                    if blob['type']=='data' and blob['id']==blob_id: located.append((pack['id'],blob))
        if len(located)!=1: raise AssertionError('expected one indexed data blob for the small east image')
        pack_id,blob=located[0]; packfile=broken/'data'/pack_id[:2]/pack_id
        packfile.resolve(strict=True).relative_to(broken.resolve()); original_pack=digest(packfile.read_bytes());size=packfile.stat().st_size
        position=blob['offset']+blob['length']//2
        with packfile.open('r+b') as f:
            f.seek(position); byte=f.read(1); f.seek(position); f.write(bytes([byte[0]^1]))
        if packfile.stat().st_size!=size or digest(packfile.read_bytes())==original_pack: raise AssertionError('corruption control was not applied')
        run('structure-damaged',broken,['check']); run('read-all-damaged',broken,['check','--read-data'],False)
        corrupt=restore('damaged',broken,good,False)
        if corrupt['passed'] or 'images/east.pgm' in corrupt['matching_files']: raise AssertionError('corruption did not affect the recovered file')
        run('read-all-original-repo-after-controls',clean,['check','--read-data'])
        retest=restore('pristine-retest',clean,good,True)
        if not retest['passed'] or manifest(src)!=original: raise AssertionError('controls changed the original source or pristine repository')
        return {'schema':1,'started_utc':started,'finished_utc':datetime.now(timezone.utc).isoformat(),
                'platform':platform.system()+' '+platform.release(),'python':platform.python_version(),'sqlite':sqlite3.sqlite_version,
                'restic':version,'executable_sha256':digest(original_copy),'transport':'local filesystem, repository format 2, no cache',
                'snapshot_ids':{'complete':good,'catalog_omitted':partial},'original_manifest':original,'command_results':events,
                'corruption':{'pack_id':pack_id,'file':'images/east.pgm','byte_offset':position,'same_size_bytes':size,
                              'before_sha256':original_pack,'after_sha256':digest(packfile.read_bytes())},
                'restores':{'complete':ok,'catalog_omitted':missing,'damaged_pack':corrupt,'pristine_retest':retest},
                'original_source_unchanged':True}


if __name__=='__main__':
    ap=argparse.ArgumentParser(description=__doc__);ap.add_argument('--restic',required=True,help='path to the restic 0.19.1 executable')
    print(json.dumps(rehearse(ap.parse_args().restic),indent=2,ensure_ascii=True))
