#!/usr/bin/env python3
"""Run the real doctor CLI on identical synthetic SQLite boundary fixtures.
Usage: python3 prove.py BASE_CHECKOUT HEAD_CHECKOUT OUTPUT_DIRECTORY
"""
import datetime, os, pathlib, sqlite3, subprocess, sys
base, head, output = map(pathlib.Path, sys.argv[1:])
run = output / datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%SZ')
run.mkdir(parents=True)
def seed(home, boundary):
    home.joinpath('userdata').mkdir(parents=True)
    db = home / 'userdata/statev2.sqlite'
    c = sqlite3.connect(db)
    c.executescript(f'PRAGMA page_size={4096 if boundary == "GiB" else 512}; PRAGMA auto_vacuum=2; CREATE TABLE blobs(data BLOB);')
    if boundary == 'GiB':
        for size in [534103034, 534103034, 3140000]:
            c.execute('INSERT INTO blobs VALUES(zeroblob(?))', (size,))
    else:
        # 2045 live pages; leave two free pages in a 2047-page file.
        size = 1028000
        c.execute('INSERT INTO blobs VALUES(zeroblob(?))', (size,))
        while c.execute('PRAGMA page_count').fetchone()[0] < 2045:
            size += 100
            c.execute('UPDATE blobs SET data=zeroblob(?)', (size,))
        c.execute('INSERT INTO blobs VALUES(zeroblob(10000))')
        c.execute('DELETE FROM blobs WHERE rowid=2')
        c.commit()
        while c.execute('PRAGMA page_count').fetchone()[0] > 2047:
            c.execute('PRAGMA incremental_vacuum(1)')
    c.commit()
    pages = c.execute('PRAGMA page_count').fetchone()[0]
    page_size = c.execute('PRAGMA page_size').fetchone()[0]
    free = c.execute('PRAGMA freelist_count').fetchone()[0]
    c.close()
    return f'page_count={pages}; page_size={page_size}; bytes={db.stat().st_size}; freelist_count={free}'
for side, checkout in [('before', base), ('after', head)]:
    sha = subprocess.check_output(['git','rev-parse','HEAD'], cwd=checkout, text=True).strip()
    lines = [f'{side.upper()} | commit {sha}', 'Environment: Linux x86_64; Node CLI; synthetic SQLite; --dry-run', '']
    for boundary in ['GiB', 'MiB']:
        home = run / f'{side}-{boundary}'
        stats = seed(home, boundary)
        lines += [f'Boundary: just under 1 {boundary}', stats, '$ node apps/server/src/bin.ts doctor --base-dir <synthetic-home> --dry-run']
        result = subprocess.run(['node','apps/server/src/bin.ts','doctor','--base-dir',str(home),'--dry-run'], cwd=checkout, env={**os.environ,'T3CODE_DEV_SEED':'0','NO_COLOR':'1'}, text=True, capture_output=True)
        lines += [result.stdout.rstrip(), result.stderr.rstrip(), f'Exit status: {result.returncode}', '']
        if result.returncode: raise RuntimeError(result.stderr)
    text = '\n'.join(lines)
    (run / f'{side}.txt').write_text(text)
    print(text)
print(f'ARTIFACTS={run}')
