#!/usr/bin/env python3
"""qg-cap — bounded pager for tool output. Reads stdin, writes the full stream to a file, prints head + tail within a cap.
usage: qg-cap <cap_chars> <store_dir>"""
import sys, os, time, hashlib
cap = int(sys.argv[1]) if len(sys.argv) > 1 else 8000
store = sys.argv[2] if len(sys.argv) > 2 else os.path.expanduser('~/.claude/quota-guard/outputs')
data = sys.stdin.buffer.read()
text = data.decode('utf-8', 'replace')
if len(text) <= cap:
    sys.stdout.write(text); sys.stdout.flush(); sys.exit(0)
os.makedirs(store, exist_ok=True)
name = time.strftime('%Y%m%d-%H%M%S') + '-' + hashlib.sha1(data).hexdigest()[:8] + '.log'
path = os.path.join(store, name)
with open(path, 'wb') as f: f.write(data)
head_n = int(cap * 0.75); tail_n = cap - head_n
omitted = len(text) - head_n - tail_n
lines = text.count('\n')
sys.stdout.write(text[:head_n])
sys.stdout.write("\n\n[quota-guard: %s chars omitted of %s (%s lines). Full output saved to %s — read it with sed -n or grep instead of re-running.]\n\n" % (f"{omitted:,}", f"{len(text):,}", f"{lines:,}", path))
sys.stdout.write(text[-tail_n:])
sys.stdout.flush()
