#!/usr/bin/env python3
"""C2 Task A + C3 (JSON) for cli-anything-libreoffice. Every command runs with --json; each result is logged.
Run with the hub venv activated and CLI_HUB_NO_ANALYTICS=1. Writes taskA/commands.jsonl and taskA/results.json."""
import json, subprocess, time, datetime, os, re, shutil, sys
W = os.path.abspath("taskA"); os.chdir(W)
for f in os.listdir('.'):
    if f != '.keep': (shutil.rmtree if os.path.isdir(f) else os.remove)(f)
LO = "cli-anything-libreoffice"
log = open("commands.jsonl", "w"); rows = []
def run(args, expect_ok=True, tag="task"):
    t0 = time.time(); ts = datetime.datetime.now().strftime("%H:%M:%S")
    p = subprocess.run([LO, "--json"] + args, capture_output=True, text=True)
    dt = round(time.time() - t0, 3)
    try: js = json.loads(p.stdout); ok_json = True
    except Exception: js = None; ok_json = False
    r = {"time_utc8": ts, "cmd": [LO, "--json"] + args, "exit": p.returncode, "secs": dt, "stdout_is_one_json_value": ok_json,
         "stdout": p.stdout[:1500], "stderr": p.stderr[:800], "tag": tag, "expect_ok": expect_ok}
    log.write(json.dumps(r) + "\n"); log.flush(); rows.append(r)
    print(f"[{ts} {dt}s exit {p.returncode} json={ok_json}] {' '.join(args)[:110]}")
    return js
T = {"heading": "Field Report 7F3A",
     "paras": ["The north survey team logged eleven soil samples before noon on Tuesday.",
               "Pump station four was offline for ninety minutes because of a tripped breaker.",
               "All readings were uploaded to the shared archive by six in the evening."],
     "cells": [["Site", "Samples", "Depth cm", "Status"], ["Alder", "4", "35", "done"], ["Birch", "7", "50", "pending"]]}
W1 = "report.lo-cli.json"
run(["document", "new", "--type", "writer", "--name", "Field Report", "-o", W1])
run(["--project", W1, "writer", "add-heading", "-t", T["heading"], "--level", "1"])
for p_ in T["paras"]: run(["--project", W1, "writer", "add-paragraph", "-t", p_])
run(["--project", W1, "writer", "add-table", "--rows", "3", "--cols", "4"])
# The CLI has no command to fill table cells (writer set-text refuses tables); try it once and record the answer.
run(["--project", W1, "writer", "set-text", "4", "Site"], expect_ok=False, tag="probe-table-cell")
run(["--project", W1, "writer", "list"])
run(["--project", W1, "document", "info"])
for fmt, ext in [("pdf", "pdf"), ("docx", "docx"), ("odt", "odt")]:
    run(["--project", W1, "export", "render", f"report.{ext}", "-p", fmt, "--overwrite"])
C1 = "sheet.lo-cli.json"
run(["document", "new", "--type", "calc", "--name", "Sums", "-o", C1])
for ref, v in [("A1", "17"), ("A2", "25"), ("A3", "58")]: run(["--project", C1, "calc", "set-cell", ref, v, "--type", "float"])
run(["--project", C1, "calc", "set-cell", "A4", "", "--formula", "=SUM(A1:A3)"])
run(["--project", C1, "calc", "get-cell", "A4"])
for fmt, ext in [("pdf", "pdf"), ("xlsx", "xlsx"), ("ods", "ods")]:
    run(["--project", C1, "export", "render", f"sheet.{ext}", "-p", fmt, "--overwrite"])
# C3 deliberate errors
run(["--project", "does-not-exist.json", "document", "info"], expect_ok=False, tag="error")
run(["--project", W1, "writer", "add-heading", "-t", "x", "--level", "notanumber"], expect_ok=False, tag="error")
run(["--project", W1, "writer", "remove", "99"], expect_ok=False, tag="error")
json.dump(rows, open("results-commands.json", "w"), indent=1)
