{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "initial_id",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-04-29T10:50:58.467758Z",
     "start_time": "2025-04-29T10:50:58.109487Z"
    }
   },
   "outputs": [],
   "source": [
    "from datetime import datetime\n",
    "import sqlite3\n",
    "\n",
    "import plotly.graph_objects as go\n",
    "import pandas as pd"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2a888e85f7940c39",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-04-29T10:51:01.444924Z",
     "start_time": "2025-04-29T10:50:58.498402Z"
    }
   },
   "outputs": [],
   "source": [
    "sqlite_file = input(\"Sqlite file: \")\n",
    "conn = sqlite3.connect(sqlite_file)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "28dd4fe644bc6a1d",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-04-29T10:54:39.597755Z",
     "start_time": "2025-04-29T10:51:01.878170Z"
    },
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "query = '''\n",
    "SELECT timestamp, filament_variant_id, available, region\n",
    "    FROM availability\n",
    "    LEFT JOIN measurements ON availability.measurement_id = measurements.id\n",
    "    LEFT JOIN filament_variants ON availability.filament_variant_id = filament_variants.id\n",
    "    LEFT JOIN filaments ON filament_variants.filament_id = filaments.id\n",
    "'''\n",
    "df = pd.read_sql(query, conn)\n",
    "\n",
    "all_timestamps = list(df['timestamp'].dropna().unique())\n",
    "all_regions = list(df['region'].dropna().unique())\n",
    "\n",
    "available = {region: [] for region in all_regions}\n",
    "not_available = {region: [] for region in all_regions}\n",
    "\n",
    "for timestamp in all_timestamps:\n",
    "    values = df.query(f'timestamp <= {timestamp}').drop(columns=['timestamp']).drop_duplicates(keep='last', subset=['filament_variant_id', 'region'])\n",
    "    \n",
    "    for region in all_regions:\n",
    "        available[region].append(len(values.query(f'(available == 1) and (region == \"{region}\")')))\n",
    "        not_available[region].append(len(values.query(f'(available == 0) and (region == \"{region}\")')))\n",
    "\n",
    "fig = go.Figure()\n",
    "for region in all_regions:\n",
    "    timestamp_datetime = [datetime.fromtimestamp(timestamp) for timestamp in all_timestamps]\n",
    "    ratios = []\n",
    "    ratio_texts = []\n",
    "    for i in range(len(available[region])):\n",
    "        ratios.append(round((available[region][i] / (available[region][i] + not_available[region][i])) * 100, 2))\n",
    "        ratio_texts.append(f'({available[region][i]} / {available[region][i] + not_available[region][i]})')\n",
    "        \n",
    "    fig.add_trace(go.Scatter(x=timestamp_datetime, y=ratios, text=ratio_texts, mode='lines', name=region.upper()))\n",
    "fig.update_layout(title='Availability', xaxis_title='Time', yaxis_title='Availability in %', yaxis_range=[0, 100], yaxis_ticksuffix = '%', hovermode='x unified')\n",
    "fig.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "597ebfa4ca856644",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-04-29T10:54:40.928058Z",
     "start_time": "2025-04-29T10:54:40.385778Z"
    }
   },
   "outputs": [],
   "source": [
    "query = '''\n",
    "SELECT timestamp, price, filament_variant_id, region\n",
    "    FROM prices\n",
    "    LEFT JOIN measurements ON prices.measurement_id = measurements.id\n",
    "    LEFT JOIN filament_variants ON prices.filament_variant_id = filament_variants.id\n",
    "    LEFT JOIN filaments ON filament_variants.filament_id = filaments.id\n",
    "'''\n",
    "df = pd.read_sql(query, conn)\n",
    "\n",
    "all_timestamps = list(df['timestamp'].dropna().unique())\n",
    "all_regions = list(df['region'].dropna().unique())\n",
    "\n",
    "price_changes = {region: [] for region in all_regions}\n",
    "\n",
    "# for timestamp in all_timestamps:\n",
    "#     values = df.query(f'timestamp == {timestamp}')\n",
    "\n",
    "#     for region in all_regions:\n",
    "#         value = values.query(f'region == \"{region}\"')\n",
    "#         if value.empty:\n",
    "#             price_changes[region].append(price_changes[region][-1])\n",
    "#         else:\n",
    "#             price_changes[region].append(values[''])\n",
    "\n",
    "# average price changes\n",
    "fig = go.Figure()\n",
    "for region in list(df['region'].dropna().unique()):\n",
    "    changed = 0\n",
    "    unchanged = 0\n",
    "    price_changes = []\n",
    "\n",
    "    for _, rows in df.query(f'(price > 0) and (region == \"{region}\")').groupby('filament_variant_id'):\n",
    "        if len(rows) == 1:\n",
    "            unchanged += 1\n",
    "            continue\n",
    "        else:\n",
    "            changed += 1\n",
    "\n",
    "        last_price = rows.iloc[0].iloc[1]\n",
    "        first_price = rows.iloc[-1].iloc[1]\n",
    "\n",
    "        price_changes.append((last_price - first_price) / first_price * 100)\n",
    "\n",
    "    price_changes_percent = sum(price_changes) / len(price_changes)\n",
    "    fig.add_trace(go.Bar(name=region, text=f'{price_changes_percent:.2f}%', x=[region], y=[price_changes_percent]))\n",
    "fig.update_layout(title='Price changes', xaxis_title='Region', yaxis_title='Price changes in %', yaxis_range=[0, 100])\n",
    "fig.show()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
