{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "title",
   "metadata": {},
   "source": [
    "# File storage\n",
    "List, upload, presign, get a download URL, delete. Each cell prints the request line (`→`) and the backend's JSON reply, signed URLs masked.\n",
    "A presigned upload is finished by PUT-ing the bytes to `upload_url`, then `client.user.register_file(...)`."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cfg-md",
   "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": "cfg",
   "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())\n\ndef masked(data):\n    return {k: \"***\" if k.endswith((\"token\", \"url\")) else v for k, v in data.items()}\n\npng = SAMPLES / \"image\" / \"samples\" / \"sample.png\""
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "list",
   "metadata": {},
   "outputs": [],
   "source": [
    "files = client.user.list_files(page_size=3)\n",
    "assert files[\"storage\"][\"limit_bytes\"] > 0\n",
    "show(files)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "upload",
   "metadata": {},
   "outputs": [],
   "source": [
    "stored = client.user.upload_file(png)\n",
    "assert stored[\"file_size_bytes\"] == png.stat().st_size\n",
    "show(stored)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "presign",
   "metadata": {},
   "outputs": [],
   "source": [
    "presigned = client.user.presign_upload(file_name=\"notes.txt\", content_type=\"text/plain\", size_bytes=12)\n",
    "assert presigned[\"upload_url\"].startswith(\"https://\") and presigned[\"s3_key\"]\n",
    "show(masked(presigned))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "download-url",
   "metadata": {},
   "outputs": [],
   "source": [
    "urls = client.user.download_files({\"file_ids\": [stored[\"id\"]]}).json()\n",
    "assert urls[\"files\"][0][\"download_url\"].startswith(\"http\")\n",
    "show([masked(f) for f in urls[\"files\"]])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "delete",
   "metadata": {},
   "outputs": [],
   "source": [
    "deleted = client.user.delete_files({\"file_ids\": [stored[\"id\"]]})\n",
    "assert stored[\"id\"] not in {f[\"id\"] for f in client.user.list_files(page_size=50)[\"results\"]}\n",
    "show(deleted)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "usage-md",
   "metadata": {},
   "source": [
    "## Usage"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "usage",
   "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
}
