{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "c0",
   "metadata": {},
   "source": [
    "# Blank forms\n",
    "Browse the public IRS/USCIS blank-form catalog with the Indox SDK: list, get one, blank download URL, its fields, then fill two fields and save the PDF."
   ]
  },
  {
   "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())\nSLUG = \"w9\"",
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "code",
   "id": "c3",
   "metadata": {},
   "source": [
    "forms = client.pdf.forms.list(source=\"irs\", q=\"w-9\", limit=3)\n",
    "show(forms)\n",
    "assert SLUG in [f[\"slug\"] for f in forms[\"items\"]]"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "code",
   "id": "c4",
   "metadata": {},
   "source": [
    "form = client.pdf.forms.get(SLUG)\n",
    "show(form)\n",
    "assert form[\"fields\"] > 0"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "code",
   "id": "c5",
   "metadata": {},
   "source": [
    "blank = client.pdf.forms.blank(SLUG)\n",
    "show({**blank, \"url\": blank[\"url\"].split(\"?\")[0] + \"?<signed query hidden>\"})\n",
    "assert blank[\"url\"].startswith(\"http\")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "code",
   "id": "c6",
   "metadata": {},
   "source": [
    "import time\n",
    "\n",
    "for _ in range(30):\n",
    "    fields = client.pdf.forms.fields(SLUG)\n",
    "    if fields.get(\"status\") != \"pending\":\n",
    "        break\n",
    "    time.sleep(2)\n",
    "show(fields)\n",
    "text = [f[\"name\"] for f in fields[\"fields\"] if f[\"type\"] == \"text\"]\n",
    "assert len(text) >= 2"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "code",
   "id": "c7",
   "metadata": {},
   "source": [
    "filled = client.pdf.forms.fill(\n",
    "    SLUG, {text[0]: \"Ada Lovelace\", text[1]: \"Analytical Engines LLC\"}, out / \"w9-filled.pdf\"\n",
    ")\n",
    "show({\"saved\": str(filled), \"bytes\": filled.stat().st_size})\n",
    "assert filled.read_bytes()[:5] == b\"%PDF-\""
   ],
   "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": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
