#!/usr/bin/env python3
"""C4 undo/redo for cli-anything-libreoffice: (a) separate one-shot invocations with --project, (b) one REPL session via stdin."""
import json, subprocess, time, datetime, os
os.chdir(os.path.abspath("taskC4"))
LO = "cli-anything-libreoffice"; rows = []; log = open("commands.jsonl", "w")
def run(args, stdin=None, tag="oneshot"):
    ts = datetime.datetime.now().strftime("%H:%M:%S"); t0 = time.time()
    p = subprocess.run([LO] + args, capture_output=True, text=True, input=stdin); dt = round(time.time() - t0, 3)
    try: js = json.loads(p.stdout); ok = True
    except Exception: js = None; ok = False
    r = {"time_utc8": ts, "cmd": [LO] + args, "stdin": stdin, "exit": p.returncode, "secs": dt, "stdout_is_one_json_value": ok,
         "stdout": p.stdout[:3000], "stderr": p.stderr[:800], "tag": tag}
    log.write(json.dumps(r) + "\n"); rows.append(r); print(f"[{ts} exit {p.returncode} json={ok}] {' '.join(args)[:100]}"); return js
P = "undo.lo-cli.json"
if os.path.exists(P): os.remove(P)
def count():
    js = run(["--json", "--project", P, "writer", "list"]); 
    return len(js) if isinstance(js, list) else (len(js.get("items", js.get("content", []))) if isinstance(js, dict) else None)
run(["--json", "document", "new", "--type", "writer", "-o", P])
for t in ["one", "two", "three"]: run(["--json", "--project", P, "writer", "add-paragraph", "-t", f"Paragraph {t}"])
res = {"oneshot": {"after_3_adds": count()}}
run(["--json", "--project", P, "session", "history"])
res["oneshot"]["undo"] = run(["--json", "--project", P, "session", "undo"])
res["oneshot"]["after_undo"] = count()
res["oneshot"]["redo"] = run(["--json", "--project", P, "session", "redo"])
res["oneshot"]["after_redo"] = count()
# (b) REPL: same steps in one process
R = "repl.lo-cli.json"
if os.path.exists(R): os.remove(R)
run(["--json", "document", "new", "--type", "writer", "-o", R])
script = "\n".join(["writer add-paragraph -t 'Paragraph one'", "writer add-paragraph -t 'Paragraph two'", "writer add-paragraph -t 'Paragraph three'",
                    "writer list", "session undo", "writer list", "session redo", "writer list", "document save", "exit"]) + "\n"
res["repl_stdout_tail"] = (run(["--project", R, "repl"], stdin=script, tag="repl") or None)
res["repl_raw"] = rows[-1]["stdout"][-2500:]
res["repl_file_after"] = json.load(open(R)).get("content") if os.path.exists(R) else None
json.dump({"results": res, "commands": rows}, open("results.json", "w"), indent=1)
print(json.dumps(res["oneshot"], indent=1)[:1500]); print(res["repl_raw"][-1800:]); print("file after repl:", res["repl_file_after"])
