{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "title",
   "metadata": {},
   "source": [
    "# Profile\n",
    "Read and edit the signed-in profile, branding and integrations. Each cell prints the request line (`→`) and the backend's JSON reply, tokens masked."
   ]
  },
  {
   "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.\n",
    "This notebook also signs in: add `INDOX_EMAIL` and `INDOX_PASSWORD` the same way."
   ]
  },
  {
   "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\nfrom indox_client import PermissionDeniedError\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": "me",
   "metadata": {},
   "outputs": [],
   "source": [
    "me = client.user.me()\n",
    "assert me[\"user\"][\"email\"]\n",
    "show(me)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "login",
   "metadata": {},
   "outputs": [],
   "source": [
    "session = client.user.login(email=get(\"INDOX_EMAIL\"), password=get(\"INDOX_PASSWORD\"))\n",
    "token = session[\"external_token\"]\n",
    "assert session[\"token_type\"] == \"Bearer\" and token\n",
    "show(masked(session))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "update",
   "metadata": {},
   "outputs": [],
   "source": [
    "old_name = me[\"user\"][\"first_name\"]\n",
    "updated = client.user.update_me(first_name=\"Ada\", access_token=token)\n",
    "assert updated[\"first_name\"] == \"Ada\"\n",
    "show(updated)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "restore",
   "metadata": {},
   "outputs": [],
   "source": [
    "restored = client.user.update_me(first_name=old_name, access_token=token)\n",
    "assert restored[\"first_name\"] == old_name\n",
    "show(restored)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "api-key-denied",
   "metadata": {},
   "outputs": [],
   "source": [
    "try:\n",
    "    client.user.update_me(first_name=\"Ada\")\n",
    "except PermissionDeniedError as exc:\n",
    "    show(exc.response)\n",
    "else:\n",
    "    raise AssertionError(\"an API key changed the profile\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "branding",
   "metadata": {},
   "outputs": [],
   "source": [
    "branding = client.user.branding()\n",
    "integrations = client.user.integrations()\n",
    "assert \"brand_color\" in branding and {i[\"provider\"] for i in integrations} >= {\"google_drive\", \"dropbox\"}\n",
    "show([masked(branding), integrations])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "avatar",
   "metadata": {},
   "outputs": [],
   "source": [
    "if png.exists():\n",
    "    avatar = client.user.upload_avatar(png)\n",
    "    removed = client.user.delete_avatar()\n",
    "    assert avatar[\"image_key\"] and removed[\"image_url\"] is None\n",
    "    show([masked(avatar), removed])\n",
    "else:\n",
    "    print(\"skipped: no sample image\")"
   ]
  },
  {
   "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())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "logout",
   "metadata": {},
   "outputs": [],
   "source": [
    "show(client.user.logout())"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
