{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "c0",
   "metadata": {},
   "source": [
    "# Office documents\n",
    "Create, read, save and delete an editor document with the Indox SDK. Import and export spend credits, so they run only with `RUN_PAID_CALLS = True`. The office editor needs a paid plan: on a free account the first cell shows the server's 403 and the rest print `skipped`."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c1",
   "metadata": {},
   "source": [
    "## Config\n",
    "Add your settings to the repo `.env` (local) or Colab **Secrets** — this cell reads them with `get(...)`:\n",
    "`INDOX_API_KEY` (your `ak_…` key) and `INDOX_BASE_URL` (`https://indox.org`; the SDK adds `/api/v1/…` itself). A missing key stops here with its name."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c2",
   "metadata": {},
   "outputs": [],
   "source": "import json, logging, re, sys, tempfile\nfrom pathlib import Path\n\nREPO = Path.cwd().parents[1]\nsys.path[:0] = [str(REPO), str(REPO / \"languages\" / \"python\")]\ntry:\n    from google.colab import userdata\n    get = userdata.get\nexcept ImportError:\n    from tools.env import require_env as get\n\nfrom indox_client import Indox\n\nlogging.basicConfig(format=\"→ %(message)s\", force=True)\nlogging.getLogger(\"urllib3.connectionpool\").setLevel(logging.DEBUG)\n\n\ndef _mask(record):\n    record.msg = re.sub(r\"/(public|sign)/[^/ ]+\", r\"/\\1/***\", record.getMessage())\n    record.args = ()\n    return True\n\n\nlogging.getLogger(\"urllib3.connectionpool\").addFilter(_mask)\n\n\ndef show(data, limit=2500):\n    print(json.dumps(data, indent=2, default=str)[:limit])\n\n\nclient = Indox(api_key=get(\"INDOX_API_KEY\"), base_url=get(\"INDOX_BASE_URL\"))\nstart_credits = client.billing.credits_balance()[\"credit_amount\"]\nSAMPLES = REPO / \"colab\"\nout = Path(tempfile.mkdtemp())\nRUN_PAID_CALLS = False"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c3",
   "metadata": {},
   "outputs": [],
   "source": [
    "from indox_client import PermissionDeniedError\n",
    "\n",
    "try:\n",
    "    documents = client.office.list_documents(page_size=5)\n",
    "    show(documents)\n",
    "except PermissionDeniedError as exc:\n",
    "    documents = None\n",
    "    print(\"403: the office editor needs a paid plan on this account\")\n",
    "    show(exc.response)\n",
    "assert documents is None or documents[\"count\"] >= len(documents[\"results\"])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c4",
   "metadata": {},
   "outputs": [],
   "source": [
    "doc = None\n",
    "if documents is not None:\n",
    "    doc = client.office.create_document(kind=\"doc\", title=\"SDK notebook doc\")\n",
    "    show(doc)\n",
    "    assert doc[\"kind\"] == \"doc\" and doc[\"id\"]\n",
    "else:\n",
    "    print(\"skipped: no office editor access\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c5",
   "metadata": {},
   "outputs": [],
   "source": [
    "if doc:\n",
    "    fetched = client.office.get_document(doc[\"id\"])\n",
    "    show(fetched)\n",
    "    assert fetched[\"id\"] == doc[\"id\"] and fetched[\"rev\"] == doc[\"rev\"]\n",
    "else:\n",
    "    print(\"skipped: no document\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c6",
   "metadata": {},
   "outputs": [],
   "source": [
    "if doc:\n",
    "    saved = client.office.save_document(\n",
    "        doc[\"id\"], rev=doc[\"rev\"], snapshot=doc[\"snapshot\"], title=\"SDK notebook doc (saved)\"\n",
    "    )\n",
    "    show(saved)\n",
    "    assert saved[\"rev\"] == doc[\"rev\"] + 1 and saved[\"title\"].endswith(\"(saved)\")\n",
    "else:\n",
    "    print(\"skipped: no document\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c7",
   "metadata": {},
   "outputs": [],
   "source": [
    "import time\n",
    "\n",
    "FINISHED = {\"completed\", \"done\", \"ready\", \"failed\"}\n",
    "\n",
    "\n",
    "def poll(fetch, done=lambda r: r[\"status\"] in FINISHED, every=3, limit=900):\n",
    "    for _ in range(limit // every):\n",
    "        resp = fetch()\n",
    "        if done(resp):\n",
    "            return resp\n",
    "        time.sleep(every)\n",
    "    raise TimeoutError(f\"still running after {limit}s\")\n",
    "\n",
    "\n",
    "if RUN_PAID_CALLS and doc:\n",
    "    job = client.office.export(doc[\"id\"], target_format=\"docx\")\n",
    "    show(poll(lambda: client.office.job(job[\"job_id\"])))\n",
    "    docx = client.office.download(job[\"job_id\"], out / \"doc.docx\")\n",
    "    job = client.office.import_file(docx, kind=\"doc\")\n",
    "    imported = poll(lambda: client.office.job(job[\"job_id\"]))\n",
    "    show(imported)\n",
    "    assert imported[\"status\"] == \"completed\" and imported[\"document_id\"]\n",
    "    client.office.delete_document(imported[\"document_id\"])\n",
    "else:\n",
    "    print(\"skipped: office.export / office.import_file spend credits (RUN_PAID_CALLS = False)\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c8",
   "metadata": {},
   "outputs": [],
   "source": [
    "if doc:\n",
    "    show(client.office.delete_document(doc[\"id\"]))\n",
    "    remaining = client.office.list_documents(page_size=100)[\"results\"]\n",
    "    assert doc[\"id\"] not in [d[\"id\"] for d in remaining]\n",
    "else:\n",
    "    print(\"skipped: no document\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c9",
   "metadata": {},
   "source": [
    "## Usage"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c10",
   "metadata": {},
   "outputs": [],
   "source": [
    "now = client.billing.credits_balance()[\"credit_amount\"]\n",
    "print(f\"credits used by this notebook: {start_credits - now}  (balance {now})\")\n",
    "show(client.billing.usage_by_feature())"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
