{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# ETL Pipelines with PyCharter\n",
    "\n",
    "Build ETL pipelines using the pipe (`|`) operator: extract from HTTP or files, transform with built-in steps, and load to files or databases.\n",
    "\n",
    "[![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/optophi/pycharter/blob/main/docs/notebooks/02_etl_pipelines.ipynb)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 1. Basic Pipeline: HTTP → Transform → File\n",
    "\n",
    "Simple HTTP extraction with transformations and file output."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import asyncio\n",
    "from pycharter import (\n",
    "    Pipeline,\n",
    "    HTTPExtractor,\n",
    "    Rename,\n",
    "    Select,\n",
    "    FileLoader,\n",
    ")\n",
    "\n",
    "pipeline = (\n",
    "    Pipeline(HTTPExtractor(url=\"https://jsonplaceholder.typicode.com/users\"))\n",
    "    | Rename({\"name\": \"full_name\"})\n",
    "    | Select([\"id\", \"full_name\", \"email\"])\n",
    "    | FileLoader(path=\"/tmp/users.json\")\n",
    ")\n",
    "\n",
    "result = asyncio.run(pipeline.run(dry_run=True))\n",
    "print(f\"Extracted: {result.rows_extracted}, Transformed: {result.rows_transformed}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 2. Transformer Showcase\n",
    "\n",
    "Demonstrate built-in transformers: Rename, AddField, Convert, Filter, Select, Drop, Default, Map."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from pycharter import Rename, AddField, Convert, Filter, Select, Drop, Default, Map\n",
    "\n",
    "sample = [\n",
    "    {\"id\": \"1\", \"name\": \"Alice\", \"score\": \"95\"},\n",
    "    {\"id\": \"2\", \"name\": \"Bob\", \"score\": \"87\"},\n",
    "]\n",
    "\n",
    "# Rename\n",
    "renamed = Rename({\"name\": \"full_name\"}).transform(sample.copy())\n",
    "print(\"Rename:\", list(renamed[0].keys()))\n",
    "\n",
    "# AddField\n",
    "with_field = AddField(\"processed\", True).transform(sample.copy())\n",
    "print(\"AddField:\", with_field[0].get(\"processed\"))\n",
    "\n",
    "# Convert\n",
    "converted = Convert({\"score\": int}).transform(sample.copy())\n",
    "print(\"Convert score type:\", type(converted[0][\"score\"]).__name__)\n",
    "\n",
    "# Filter\n",
    "filtered = Filter(lambda r: int(r[\"score\"]) > 90).transform(sample.copy())\n",
    "print(\"Filter (score > 90):\", len(filtered), \"records\")\n",
    "\n",
    "# Select\n",
    "selected = Select([\"id\", \"name\"]).transform(sample.copy())\n",
    "print(\"Select:\", list(selected[0].keys()))\n",
    "\n",
    "# Drop\n",
    "dropped = Drop([\"score\"]).transform(sample.copy())\n",
    "print(\"Drop:\", list(dropped[0].keys()))\n",
    "\n",
    "# Default\n",
    "with_defaults = Default({\"age\": 0}).transform(sample.copy())\n",
    "print(\"Default age:\", with_defaults[0].get(\"age\"))\n",
    "\n",
    "# Map\n",
    "mapped = Map(lambda r: {**r, \"name_upper\": r[\"name\"].upper()}).transform(sample.copy())\n",
    "print(\"Map name_upper:\", mapped[0].get(\"name_upper\"))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 3. Chained Transformations\n",
    "\n",
    "Chain multiple transformers in one pipeline."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "pipeline = (\n",
    "    Pipeline(HTTPExtractor(url=\"https://jsonplaceholder.typicode.com/posts\"))\n",
    "    | Select([\"id\", \"userId\", \"title\"])\n",
    "    | Rename({\"userId\": \"user_id\"})\n",
    "    | AddField(\"source\", \"jsonplaceholder\")\n",
    "    | Filter(lambda r: r[\"user_id\"] == 1)\n",
    "    | FileLoader(path=\"/tmp/posts.json\")\n",
    ")\n",
    "\n",
    "result = asyncio.run(pipeline.run(dry_run=True))\n",
    "print(f\"Extracted: {result.rows_extracted}, After filter: {result.rows_transformed}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 4. File Extraction\n",
    "\n",
    "Extract from local files (CSV, JSON, JSONL, Parquet, Excel). Format is auto-detected from extension or set via `file_format`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from pycharter import FileExtractor\n",
    "\n",
    "# FileExtractor(path=\"data.json\")  # format auto-detected\n",
    "# FileExtractor(path=\"data.csv\", file_format=\"csv\")\n",
    "# Supported: csv, json, jsonl, parquet, excel\n",
    "# Glob: path=\"data/*.csv\"\n",
    "print(\"FileExtractor supports: CSV, JSON, JSONL, Parquet, Excel and glob patterns\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 5. Config-Driven Pipelines\n",
    "\n",
    "Load pipelines from YAML: `Pipeline.from_config_dir(\"pipeline/\")` with `extract.yaml`, `transform.yaml`, `load.yaml`. Use `Pipeline.from_config_files(extract=..., transform=..., load=..., variables={...})` for explicit paths."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# pipeline = Pipeline.from_config_dir(\"pipelines/users_etl/\", variables={\"DATA_DIR\": \"./data\", \"OUTPUT_DIR\": \"./output\"})\n",
    "# result = asyncio.run(pipeline.run())\n",
    "print(\"Use Pipeline.from_config_dir() or Pipeline.from_config_files() for YAML-driven ETL\")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python",
   "version": "3.10.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
