"""Run from the extracted agent-approval-lab directory. Synthetic local actions only."""
import argparse
from contextlib import closing
import json
from pathlib import Path
import sqlite3
import sys


def status(store):
    if not (store / "ledger.sqlite").is_file():
        raise ValueError("No run exists here. Run start with a new --store path first.")
    with closing(sqlite3.connect((store / "ledger.sqlite").as_uri() + "?mode=ro", uri=True)) as db:
        row = db.execute("SELECT action, status FROM request WHERE id=1").fetchone()
        if row is None:
            raise ValueError("Incomplete store. Inspect it; do not reuse it for a new action.")
        actions = [json.loads(item[0]) for item in db.execute("SELECT action FROM effects ORDER BY id")]
    return {"status": row[1], "action": json.loads(row[0]), "mock_effects": actions}


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("command", choices=["start", "approve", "reject", "status"])
    parser.add_argument("--store", required=True, type=Path)
    args = parser.parse_args()
    # The public script reuses the pinned lab, including its actual JavaScript SDK worker.
    if not (Path.cwd() / "lab.py").is_file():
        raise ValueError("Run this script from the extracted agent-approval-lab directory.")
    sys.path.insert(0, str(Path.cwd()))
    from lab import ACTION, NOW, PRINCIPAL, create, decide, dispatch, worker
    store = args.store.resolve()
    if args.command == "start":
        # Never overwrite a pending decision, completed run, or unrelated existing directory.
        store.mkdir(parents=True, exist_ok=False)
        create("openai", store, guarded=True)
    elif args.command != "status":
        current = status(store)
        if current["status"] == "pending":
            approved = args.command == "approve"
            decision = decide(store, PRINCIPAL, approved, NOW)
            if decision["status"] == "approved":
                dispatch("openai", store, ACTION, NOW)
            elif decision["status"] == "rejected":
                worker("openai", store, "resume", approved=False, guarded=True)
        # A prior decision is never reversed or automatically retried. A crash between
        # decision, consumption and SDK completion requires operator reconciliation.
    print(json.dumps(status(store), indent=2))


if __name__ == "__main__":
    try:
        main()
    except (ValueError, OSError, RuntimeError, sqlite3.Error) as error:
        print(str(error), file=sys.stderr)
        sys.exit(2)
