#!/usr/bin/env python3
# Tests catch.py with standard-input cases, on a temporary copy inside this folder.
import json, os, shutil, subprocess, sys, tempfile

here = os.path.dirname(os.path.abspath(__file__))
ok_all = True

def run(tmp, stdin):
    p = subprocess.run([sys.executable, os.path.join(tmp, "catch.py")], input=stdin,
                       capture_output=True, text=True)
    return p.returncode, p.stdout

def report(name, ok, detail=""):
    global ok_all
    ok_all &= ok
    print("%s  %s %s" % ("ok  " if ok else "BAD ", name, detail))

def fresh():
    tmp = tempfile.mkdtemp(prefix=".hooktest-", dir=here)
    shutil.copy(os.path.join(here, "catch.py"), tmp)
    return tmp

tmp = fresh()
try:
    out_file = os.path.join(tmp, "corrections.jsonl")
    # 1. two No, actually lines in one message
    prompt = "hi\nNo, actually I want yoga first\nmiddle line\nNO, ACTUALLY shifts are 8a now\n"
    code, out = run(tmp, json.dumps({"prompt": prompt}))
    rows = [json.loads(l) for l in open(out_file)]
    report("two lines in one message", code == 0 and out == "" and len(rows) == 2
           and rows[0]["message"] == rows[1]["message"]
           and rows[0]["words"] == "No, actually I want yoga first"
           and rows[1]["words"] == "NO, ACTUALLY shifts are 8a now"
           and rows[0]["time"].endswith("Z"), json.dumps(rows))
    # 2. No, actually only in the middle of a line
    code, out = run(tmp, json.dumps({"prompt": "I said no, actually that is fine"}))
    rows2 = [json.loads(l) for l in open(out_file)]
    report("No, actually in the middle only", code == 0 and out == "" and len(rows2) == 2)
    # 3. input that is not JSON
    code, out = run(tmp, "not json at all")
    report("input not JSON", code == 0 and json.loads(out)["systemMessage"].startswith("Correction NOT saved:"), out.strip())
finally:
    shutil.rmtree(tmp, ignore_errors=True)

tmp = fresh()
try:
    # 4. save fails: corrections.jsonl is a folder
    os.mkdir(os.path.join(tmp, "corrections.jsonl"))
    code, out = run(tmp, json.dumps({"prompt": "No, actually dinner is at 8p"}))
    report("save fails (folder)", code == 0 and json.loads(out)["systemMessage"].startswith("Correction NOT saved:"), out.strip())
finally:
    shutil.rmtree(tmp, ignore_errors=True)

print("PASS" if ok_all else "FAIL")
sys.exit(0 if ok_all else 1)
