#!/usr/bin/env python3
"""Made-up export and sealed-backup regression checks."""
import hashlib
import io
import json
import os
import pathlib
import shutil
import subprocess
import sys
import tarfile
import tempfile
import zipfile

ROOT = pathlib.Path(__file__).resolve().parents[2]
EXPORT = ROOT / 'engine/bin/export'
BACKUP = ROOT / 'engine/bin/backup'
NEW = ROOT / 'engine/bin/new-folder'

def run(*args, code=0, input=None):
    p = subprocess.run([str(a) for a in args], input=input, text=True, capture_output=True)
    assert p.returncode == code, (args, p.returncode, p.stdout, p.stderr)
    return p.stdout

def snapshot(root):
    return {str(p.relative_to(root)): p.read_bytes() for p in root.rglob('*') if p.is_file() and p.relative_to(root).parts[0] != '.summary'}

def check():
    with tempfile.TemporaryDirectory(prefix='argoni-export-test-') as t:
        t = pathlib.Path(t)
        life = t / 'Alex'
        run(NEW, life, '--demo')
        data = life / 'data'
        (data / '.summary').mkdir(exist_ok=True)
        (data / '.summary/canary').write_text('CACHE CANARY')
        (data / '.memory').mkdir(exist_ok=True)
        (data / '.memory/canary').write_text('INDEX CANARY')
        (data / '.trash').mkdir(exist_ok=True)
        (data / '.trash/canary').write_text('TRASH CANARY')
        # S2: only the exact cache location is skipped; user names survive.
        for rel in ('projects/garden/trash/compost.md', 'ideas/imported/i.md', 'work/restored/r.md', 'imported/older.md', '.hidden.md', 'projects/garden/.memory/note.md'):
            p = data / rel; p.parent.mkdir(parents=True, exist_ok=True); p.write_text('USER ' + rel)
        # S3: a restore must bring back the history store, byte for byte.
        (data / '.git').mkdir(exist_ok=True)
        (data / '.git/HEAD').write_bytes(b'ref: refs/heads/main\n')
        cfg = json.loads((data / 'config.json').read_text())
        cfg['api_key'] = 'SECRET-KEY-CANARY'
        (data / 'config.json').write_text(json.dumps(cfg))
        (data / 'jobs.json').write_text(json.dumps({'user': [{'name': 'mine'}], 'merged': 'MERGED CANARY'}))
        archive = t / 'export.zip'
        chat = json.dumps({'messages': [{'role':'user','date':'2026-10-28T12:00:00Z','text':'Hello'}]})
        run(EXPORT, life, archive, '--chat-json', '-', input=chat)
        run(EXPORT, life, archive, code=3)
        with zipfile.ZipFile(archive) as z:
            names = set(z.namelist())
            assert {'README.txt', 'manifest.json', 'settings.json', 'spending.csv', 'chat/2026-10-28.md'} <= names
            assert any(n.startswith('decisions/') for n in names)
            assert any(n.startswith('people/') for n in names)
            assert {'projects/garden/trash/compost.md', 'ideas/imported/i.md', 'notes/work/restored/r.md', 'notes/imported/older.md'} <= names, 'S2: user folders named trash, imported, or restored must export'
            manifest = json.loads(z.read('manifest.json'))
            assert manifest['shape'] == 1
            for e in manifest['files']:
                b = z.read(e['path'])
                assert len(b) == e['size'] and hashlib.sha256(b).hexdigest() == e['sha256']
            allbytes = b'\n'.join(z.read(n) for n in names)
            for marker in (b'CACHE CANARY', b'INDEX CANARY', b'TRASH CANARY', b'SECRET-KEY-CANARY', b'MERGED CANARY'):
                assert marker not in allbytes
            manual = [line.encode() for line in (life/'engine/AGENTS.md').read_text().splitlines() if len(line) > 75 and not line.startswith('#')]
            skills = [line.encode() for p in (life/'engine/skills').glob('*/SKILL.md') for line in p.read_text().splitlines() if len(line) > 75 and not line.startswith('#')]
            assert len(manual) >= 10 and len(skills) >= 10
            for line in manual[:10] + skills[:10]:
                assert line not in allbytes
        plan = json.loads(run(EXPORT, '--check', archive, life))
        assert 'settings.json' in plan['proposals']
        assert any(n.startswith('data/imported/') for n in plan['imported'])
        entries = {e['path']: e for e in manifest['files']}
        contents = {n: zipfile.ZipFile(archive).read(n) for n in names}
        def crafted(name, payload=b'x', amend=True, mode=None):
            files = dict(contents)
            files[name] = payload
            man = json.loads(files['manifest.json'])
            if amend:
                man['files'].append({'path':name,'sha256':hashlib.sha256(payload).hexdigest(),'size':len(payload)})
                files['manifest.json'] = json.dumps(man).encode()
            path = t / ('bad-%d.zip' % len(list(t.glob('bad-*.zip'))))
            with zipfile.ZipFile(path, 'w') as z:
                for n,b in files.items():
                    if n == name and mode is not None:
                        info = zipfile.ZipInfo(n)
                        info.create_system = 3
                        info.external_attr = mode << 16
                        z.writestr(info,b)
                    else: z.writestr(n,b)
            return path
        for name in ('../out', '/tmp/out', 'notes/ME/profile.md', 'notes/me/../out'):
            run(EXPORT, '--check', crafted(name), life, code=3)
        run(EXPORT, '--check', crafted('notes/link', mode=0o120777), life, code=3)
        # A single archive with two names that normalize to the same path.
        pair = t / 'clash.zip'
        with zipfile.ZipFile(pair, 'w') as z:
            z.writestr('notes/cafe\u0301.md', b'a')
            z.writestr('notes/café.md', b'b')
        run(EXPORT, '--check', pair, life, code=3)
        run(EXPORT, '--check', crafted('notes/added.md', amend=False), life, code=3)
        jobzip = crafted('notes/jobs.json', b'{}')
        assert 'notes/jobs.json' in json.loads(run(EXPORT, '--check', jobzip, life))['proposals']
        # S1: every routing and proposal rule compares NFC plus casefold.
        for name in ('notes/Jobs.json', 'NOTES/CONFIG.JSON', 'notes/ME/orders.md', 'Notes/Me\u0301/../x'):
            if '/..' in name:
                run(EXPORT, '--check', crafted(name), life, code=3)
            else:
                assert name in json.loads(run(EXPORT, '--check', crafted(name), life))['proposals'], 'S1: protected case variant must be proposed: ' + name
        for name in ('notes/.git/hooks/pre-commit', 'notes/.proposals/p1.json', 'notes/.archive-in/a.md', 'notes/.summary/memory.sqlite', 'notes/.hidden.md'):
            run(EXPORT, '--check', crafted(name), life, code=3)
        for name in ('notes/imported/new.md', 'notes/restored/new.md'):
            plan = json.loads(run(EXPORT, '--check', crafted(name), life))
            assert name not in plan['add'] and name in plan['proposals'], 'S1: internal landing area must not be a plain add'
        # The reader's real-byte cap handles a highly compressed member.
        bomb = t / 'bomb.zip'
        with zipfile.ZipFile(bomb, 'w', zipfile.ZIP_DEFLATED) as z:
            z.writestr('huge', b'0' * (64 * 1024 * 1024 + 1))
        run(EXPORT, '--check', bomb, life, code=3)
        out = t / 'backups'; out.mkdir()
        run(BACKUP, life, out)
        backup = next(out.iterdir())
        run(BACKUP, life, out, code=3)
        run(BACKUP, '--check', backup)
        damaged = t / 'damaged.argonibackup'
        damaged.write_bytes(backup.read_bytes()[:-1] + b'X')
        run(BACKUP, '--check', damaged, code=3)
        sealed = backup.read_bytes()
        assert b'profile.md' not in sealed and b'An open-source CLI' not in sealed
        restored = t / 'restored'
        run(BACKUP, 'restore', backup, restored)
        assert (restored/'data/.git/HEAD').read_bytes() == (data/'.git/HEAD').read_bytes(), 'S3: history must return on restore'
        assert snapshot(data) == snapshot(restored/'data')
        run(BACKUP, 'restore', backup, restored, code=3)
        # Six valid named files; newest four retained, two printed, none removed.
        for day in range(1, 7):
            (out / ('Argoni Backup 2026-10-%02d 0100.argonibackup' % day)).write_bytes(sealed)
        listed = run(BACKUP, '--old', out).splitlines()
        assert len(listed) == 3 and len(list(out.iterdir())) == 7
    print('export-test: OK')

if __name__ == '__main__':
    check()
