"""Compare RTK's accounting with the requested one-line read on a private fixture."""
import json
import os
from pathlib import Path
import sqlite3
import subprocess
import sys
import tempfile
from contextlib import closing

binary = str(Path(sys.argv[1]).resolve())
with tempfile.TemporaryDirectory(prefix='rtk-accounting-') as folder:
    root = Path(folder)
    fixture = root / 'fixture.txt'
    raw = ''.join(f'line {i:04d} value 42\n' for i in range(1000)).encode()
    fixture.write_bytes(raw)
    env = dict(os.environ, RTK_DB_PATH=str(root / 'history.db'), NO_COLOR='1')
    rewrite = subprocess.run([binary, 'rewrite', 'head -1 fixture.txt'], cwd=root,
                             env=env, capture_output=True)
    print('rewrite exit:', rewrite.returncode)
    print('rewrite:', rewrite.stdout.decode().strip())
    filtered = subprocess.run([binary, 'read', 'fixture.txt', '--max-lines', '1'],
                              cwd=root, env=env, capture_output=True, check=True)
    print('rtk stdout:', json.dumps(filtered.stdout.decode()))
    baseline = raw.splitlines(keepends=True)[0]
    print(f'bytes: full_file={len(raw)}, one_line_baseline={len(baseline)}, rtk_stdout={len(filtered.stdout)}')
    gain = subprocess.run([binary, 'gain', '--format', 'json'], cwd=root,
                          env=env, capture_output=True, check=True)
    print('gain:', gain.stdout.decode().strip())
    with closing(sqlite3.connect(root / 'history.db')) as db:
        db.row_factory = sqlite3.Row
        record = dict(db.execute('select * from commands order by id desc limit 1').fetchone())
        print('accounting:', json.dumps({key: record[key] for key in
             ['original_cmd', 'rtk_cmd', 'input_tokens', 'output_tokens', 'saved_tokens'] if key in record}))
