{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "c0",
   "metadata": {},
   "source": [
    "# Conversion lifecycle\n",
    "Convert a PDF, then manage the result with the Indox SDK: keep policy, save to My Files, retry (only a failed conversion re-runs) and email (`SEND_EMAILS`)."
   ]
  },
  {
   "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",
   "id": "c2",
   "metadata": {},
   "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())\npdf = SAMPLES / \"pdf\" / \"samples\" / \"bitcoin.pdf\"\nSEND_EMAILS = False",
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "code",
   "id": "c3",
   "metadata": {},
   "source": [
    "job = client.pdf.convert(pdf, target_format=\"pdf\")\n",
    "done = client.pdf.wait(job[\"id\"])\n",
    "show(done)\n",
    "assert done[\"status\"] == \"completed\""
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "code",
   "id": "c4",
   "metadata": {},
   "source": [
    "kept = client.pdf.set_keep_policy(job[\"id\"], \"30d\")\n",
    "show(kept)\n",
    "assert kept[\"keep_policy\"] == \"30d\""
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "code",
   "id": "c5",
   "metadata": {},
   "source": [
    "saved = client.pdf.save_to_files(job[\"id\"])\n",
    "show(saved)\n",
    "assert saved[\"size_bytes\"] > 0"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "code",
   "id": "c6",
   "metadata": {},
   "source": [
    "from indox_client import APIStatusError\n",
    "\n",
    "try:\n",
    "    retried = client.pdf.retry(job[\"id\"])\n",
    "except APIStatusError as exc:\n",
    "    assert exc.status_code == 409, exc\n",
    "    retried = exc.response\n",
    "show(retried)\n",
    "assert retried[\"status\"] in (\"pending\", \"completed\")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "code",
   "id": "c7",
   "metadata": {},
   "source": [
    "if SEND_EMAILS:\n",
    "    files = client.user.list_files(page_size=20)\n",
    "    s3_key = next(f[\"s3_key\"] for f in files[\"results\"] if f[\"id\"] == saved[\"user_file_id\"])\n",
    "    emailed = client.pdf.email(s3_key, filename=saved[\"file_name\"])\n",
    "    show(emailed)\n",
    "else:\n",
    "    print(\"skipped: pdf.email sends the file to your verified address (SEND_EMAILS = False)\")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "c8",
   "metadata": {},
   "source": [
    "## Usage"
   ]
  },
  {
   "cell_type": "code",
   "id": "c9",
   "metadata": {},
   "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())"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "code",
   "id": "c10",
   "metadata": {},
   "source": [
    "removed = client.user.delete_files({\"file_ids\": [saved[\"user_file_id\"]]})\n",
    "show(removed)\n",
    "for cid in {job[\"id\"], retried.get(\"id\", job[\"id\"])}:\n",
    "    client.conversion.delete(cid)"
   ],
   "execution_count": null,
   "outputs": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
