"""One synthetic state rollout. --dry-run prints input without an API call."""
import argparse
import json
from pathlib import Path
import sys
import uuid

# Downloaded copies live beside their client; the repository keeps it in sdk/python.
if not Path(__file__).with_name("kinejing_client.py").is_file():
    sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "sdk" / "python"))
from kinejing_client import KineJingClient, KineJingError, MODEL

CONTEXT = [[230.0, 230.0, 256.0, 256.0, 0.1], [231.0, 232.0, 256.0, 256.0, 0.1]]
ACTIONS = [[280.0, 280.0], [290.0, 280.0], [300.0, 280.0]]


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--dry-run", action="store_true", help="No key or network call required")
    parser.add_argument("--idempotency-key", help="Reuse this key only for the identical logical request")
    parser.add_argument("--out", type=Path, help="Save the full result to a new local JSON file")
    args = parser.parse_args()
    if args.out and args.out.exists():
        parser.error("--out must name a new file; retain earlier successful results")
    if args.dry_run:
        print(json.dumps({"model": MODEL, "state_schema": "pusht-512xy-angle-rad-v1",
                          "action_schema": "pusht-absolute-xy-10hz-v1",
                          "context_states": CONTEXT, "actions": ACTIONS}, indent=2))
        return 0
    idem = args.idempotency_key or uuid.uuid4().hex
    try:
        result = KineJingClient().rollout(CONTEXT, ACTIONS, idempotency_key=idem)
    except KineJingError as error:
        print(json.dumps({"error": str(error), "status": error.status,
                          "request_id": error.request_id, "receipt": error.receipt,
                          "idempotency_key": error.idempotency_key}, ensure_ascii=True), file=sys.stderr)
        return 1
    except ValueError as error:
        print(str(error), file=sys.stderr)
        return 1
    if args.out:
        with args.out.open("x", encoding="utf-8") as output:
            json.dump(result, output, ensure_ascii=True, indent=2)
            output.write("\n")
    print(json.dumps({"request_id": result.get("request_id"), "attempt_request_id": result.get("_request_id"), "model": result.get("model"),
                      "checkpoint_sha256": result.get("checkpoint_sha256"),
                      "predicted_steps": len(result.get("predicted_states", [])),
                      "billing": result.get("billing"), "usage_receipt": result.get("usage_receipt"),
                      "idempotency_key": idem, "synthetic_input": True}, ensure_ascii=True))
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
