"""Exercise the original hook programs without installing hooks or invoking models.

python shunt-probe.py CHECKOUT --bash /path/to/bash --jq-dir /path/containing/jq
"""
import argparse, json, os, pathlib, subprocess, tempfile
p = argparse.ArgumentParser()
p.add_argument('checkout', type=pathlib.Path)
p.add_argument('--bash', default='bash')
p.add_argument('--jq-dir', default='')
a = p.parse_args()
env = dict(os.environ)
env.pop('SHUNT_MIN_LINES', None)
if a.jq_dir: env['PATH'] = str(pathlib.Path(a.jq_dir).resolve()) + os.pathsep + env['PATH']
hooks = a.checkout.resolve() / 'plugins/shunt/hooks'
results = []
with tempfile.TemporaryDirectory(prefix='shunt-probe-') as temp:
    root = pathlib.Path(temp)
    for count in [350, 351]:
        (root / f'lines{count}.txt').write_text('fixture\n' * count, encoding='utf-8')
    small = (root / 'lines350.txt').as_posix()
    large = (root / 'lines351.txt').as_posix()
    cases = [
        ('350 lines', 'check-file-size', {'file_path': small}, 'allow'),
        ('351 lines', 'check-file-size', {'file_path': large}, 'block'),
        ('limit 1', 'check-file-size', {'file_path': large, 'limit': 1}, 'allow'),
        ('offset 1', 'check-file-size', {'file_path': large, 'offset': 1}, 'allow'),
        ('plain cat', 'check-bash-read', {'command': f'cat "{large}"'}, 'block'),
        ('cat piped to cat', 'check-bash-read', {'command': f'cat "{large}" | cat'}, 'allow'),
    ]
    for name, hook, tool_input, expected in cases:
        proc = subprocess.run([a.bash, (hooks / hook).as_posix()], input=json.dumps({'tool_input': tool_input}),
                              text=True, capture_output=True, env=env, check=True)
        decision = json.loads(proc.stdout)['decision']
        assert decision == expected, (name, proc.stdout, proc.stderr)
        results.append({'case': name, 'decision': decision})
print(json.dumps(results, indent=2))
