#!/usr/bin/env python3
"""Bab 03 — Python Data Lab.

Bisa dijalankan sebagai file .py lokal, dibaca di VS Code, dan isi logikanya
sama dengan notebook `python_data_lab.ipynb`. Script ini sengaja hanya memakai
Python standard library agar mudah berjalan di local, Jupyter, Colab, dan Kaggle.
"""
from __future__ import annotations

from datetime import datetime
import platform
import random
from statistics import mean

SEED = 42
random.seed(SEED)

DATA = [
    {"tanggal": "2026-01-01", "cuaca": "panas", "hari": "libur", "es_teh": 42, "kopi": 18},
    {"tanggal": "2026-01-02", "cuaca": "hujan", "hari": "kerja", "es_teh": 18, "kopi": 31},
    {"tanggal": "2026-01-03", "cuaca": "panas", "hari": "kerja", "es_teh": 35, "kopi": 22},
    {"tanggal": "2026-01-04", "cuaca": "berawan", "hari": "libur", "es_teh": 30, "kopi": 24},
    {"tanggal": "2026-01-05", "cuaca": "hujan", "hari": "kerja", "es_teh": 16, "kopi": 34},
    {"tanggal": "2026-01-06", "cuaca": "panas", "hari": "kerja", "es_teh": 38, "kopi": 21},
    {"tanggal": "2026-01-07", "cuaca": "panas", "hari": "libur", "es_teh": 45, "kopi": 20},
]


def total(row: dict) -> int:
    return row["es_teh"] + row["kopi"]


def average(rows: list[dict], key: str) -> float:
    return mean(row[key] for row in rows)


def average_when(rows: list[dict], key: str, filter_key: str, filter_value: str) -> float:
    selected = [row[key] for row in rows if row[filter_key] == filter_value]
    return mean(selected) if selected else 0.0


def best_day(rows: list[dict]) -> dict:
    return max(rows, key=total)


def baseline_prediction(rows: list[dict], key: str) -> int:
    """Baseline paling sederhana: prediksi besok = rata-rata historis."""
    return round(average(rows, key))


def print_table(rows: list[dict]) -> None:
    print("tanggal     cuaca    hari   es_teh  kopi  total")
    print("-" * 52)
    for row in rows:
        print(f"{row['tanggal']}  {row['cuaca']:<7}  {row['hari']:<5}  {row['es_teh']:>6}  {row['kopi']:>4}  {total(row):>5}")


def run_analysis(rows: list[dict]) -> dict:
    result = {
        "rata_es_teh": average(rows, "es_teh"),
        "rata_kopi": average(rows, "kopi"),
        "rata_es_teh_panas": average_when(rows, "es_teh", "cuaca", "panas"),
        "rata_kopi_hujan": average_when(rows, "kopi", "cuaca", "hujan"),
        "hari_tertinggi": best_day(rows),
        "baseline_es_teh": baseline_prediction(rows, "es_teh"),
        "baseline_kopi": baseline_prediction(rows, "kopi"),
    }
    return result


def print_run_note() -> None:
    print("\nCatatan run")
    print("-" * 52)
    print(f"Waktu       : {datetime.now().isoformat(timespec='seconds')}")
    print(f"Python      : {platform.python_version()}")
    print(f"Platform    : {platform.platform()}")
    print(f"Seed        : {SEED}")
    print("Dependency  : Python standard library only")


def main() -> None:
    print("Bab 03 — Python Data Lab")
    print_table(DATA)
    result = run_analysis(DATA)
    print("\nRingkasan")
    print("-" * 52)
    print(f"Rata-rata es teh          : {result['rata_es_teh']:.2f}")
    print(f"Rata-rata kopi            : {result['rata_kopi']:.2f}")
    print(f"Rata-rata es teh saat panas: {result['rata_es_teh_panas']:.2f}")
    print(f"Rata-rata kopi saat hujan  : {result['rata_kopi_hujan']:.2f}")
    best = result["hari_tertinggi"]
    print(f"Hari total tertinggi       : {best['tanggal']} ({total(best)} minuman)")
    print("\nBaseline prediksi besok")
    print("-" * 52)
    print(f"Es teh: {result['baseline_es_teh']} gelas")
    print(f"Kopi  : {result['baseline_kopi']} gelas")
    print_run_note()


if __name__ == "__main__":
    main()
