"""Normalize twelve complete anonymous monthly electricity bill records.""" from datetime import date import hashlib import json import math ALLOWED = {"month", "kwh", "billed_total", "currency", "peak_kwh"} def finite(value, field): if isinstance(value, bool): raise ValueError(f"Bill {field} must be a nonnegative number.") try: value = float(value) except (ValueError, TypeError): raise ValueError(f"Bill {field} must be a nonnegative number.") from None if not math.isfinite(value) or not 0 <= value <= 1e8: raise ValueError(f"Bill {field} must be a finite nonnegative number.") return value def normalize_bills(records, currency, as_of): if not isinstance(records, list) or len(records) != 12: raise ValueError("billing_months needs exactly 12 complete monthly records.") end = as_of.year * 12 + as_of.month - 1 expected = {f"{i // 12:04d}-{i % 12 + 1:02d}" for i in range(end - 12, end)} normalized, seen = [], set() has_peak = [isinstance(r, dict) and "peak_kwh" in r for r in records] if any(has_peak) and not all(has_peak): raise ValueError("Supply peak_kwh for every month or omit it for every month.") for r in records: if not isinstance(r, dict) or set(r) - ALLOWED: raise ValueError("Bill records accept only month,kwh,billed_total,currency,peak_kwh; remove personal fields.") if not {"month", "kwh", "billed_total", "currency"} <= set(r): raise ValueError("Each bill needs month,kwh,billed_total,currency.") month = r["month"] if month not in expected or month in seen: raise ValueError("Bills must cover each of the latest 12 complete months once, using YYYY-MM.") if r["currency"] != currency: raise ValueError("Every bill currency must match the market.") seen.add(month) kwh, billed = finite(r["kwh"], "kwh"), finite(r["billed_total"], "billed_total") row = {"month": month, "kwh": kwh, "billed_total": billed, "currency": currency} if all(has_peak): row["peak_kwh"] = finite(r["peak_kwh"], "peak_kwh") if row["peak_kwh"] > kwh: raise ValueError("peak_kwh cannot exceed total kwh.") normalized.append(row) normalized.sort(key=lambda r: r["month"]) usage = sum(r["kwh"] for r in normalized) if usage < 1: raise ValueError("Annual consumption from bills must be at least 1 kWh.") result = {"annual_kwh": usage, "current_annual_bill": sum(r["billed_total"] for r in normalized), "profile_source": "latest_12_complete_monthly_bills", "period_start": normalized[0]["month"], "period_end": normalized[-1]["month"], "input_sha256": hashlib.sha256(json.dumps(normalized, sort_keys=True).encode()).hexdigest(), "forecast_status": "Historical usage scenario; no household model winner inferred from 12 monthly bills."} if all(has_peak): result["peak_share"] = sum(r["peak_kwh"] for r in normalized) / usage return result