""" utils.py — Funzioni helper: formatter, session state, async runner. Nessuna chiamata API o rendering Streamlit diretto qui. """ import asyncio from datetime import datetime from typing import Any, Awaitable import pandas as pd import streamlit as st from config import ( AUTO_REFRESH_DEFAULT_SECONDS, BATTERY_CAPACITY_BY_VCD, BATTERY_CAPACITY_DEFAULT_KWH, DEBUG_LOG_LIMIT, ) # ─── Segreti ───────────────────────────────────────────────────────────────── def safe_secret(key: str, default: str = "") -> str: try: return st.secrets.get(key, default) except Exception: return default # ─── Session state ──────────────────────────────────────────────────────────── def init_state() -> None: defaults: dict[str, Any] = { "autenticato": False, "dati_auto": None, "ultimo_refresh": None, "ultimo_errore": None, "email_input": "", "password_input": "", "_hidden_password": "", "auto_refresh_enabled": False, "auto_refresh_seconds": AUTO_REFRESH_DEFAULT_SECONDS, "lookback_days": 180, "map_zoom": 15, "debug_events": [], "costo_kwh": 0.25, "vehicle_list": [], "renault_vin_selected": None, } for key, value in defaults.items(): if key not in st.session_state: st.session_state[key] = value def get_current_credentials() -> tuple[str, str]: email = str(st.session_state.get("email_input", "")).strip() password = str(st.session_state.get("_hidden_password", "")) if not password: password = str(st.session_state.get("password_input", "")) return email, password # ─── Debug log ──────────────────────────────────────────────────────────────── def add_debug_event(message: str, level: str = "info") -> None: event = { "Ora": datetime.now().strftime("%d/%m/%Y %H:%M:%S"), "Livello": level.upper(), "Messaggio": message, } events = [event] + st.session_state.get("debug_events", []) st.session_state["debug_events"] = events[:DEBUG_LOG_LIMIT] # ─── Async runner ───────────────────────────────────────────────────────────── def run_async(coro: Awaitable[Any]) -> Any: try: return asyncio.run(coro) except RuntimeError: loop = asyncio.new_event_loop() try: asyncio.set_event_loop(loop) return loop.run_until_complete(coro) finally: loop.close() asyncio.set_event_loop(None) # ─── Accesso sicuro ad oggetti / dict ───────────────────────────────────────── def safe_get(obj: Any, *names: str, default: Any = None) -> Any: if obj is None: return default for name in names: if isinstance(obj, dict) and name in obj: value = obj.get(name) if value is not None: return value if hasattr(obj, name): value = getattr(obj, name) if value is not None: return value return default # ─── Rilevamento capacità batteria da VCD ───────────────────────────────────── # FIX #11/#15 — capacità batteria rilevata dinamicamente, non più hardcoded def detect_battery_capacity_kwh(vcd_string: str | None) -> float: """ Legge il VCD del veicolo e restituisce la capacità reale della batteria in kWh. Fallback a BATTERY_CAPACITY_DEFAULT_KWH se non rilevabile. """ if not vcd_string: return BATTERY_CAPACITY_DEFAULT_KWH codes = {c.strip().upper() for c in vcd_string.split("/") if c.strip()} for code, kwh in BATTERY_CAPACITY_BY_VCD.items(): if code in codes: return kwh return BATTERY_CAPACITY_DEFAULT_KWH # ─── Estrazione / normalizzazione valori ───────────────────────────────────── def extract_display_value(value: Any, fallback: str = "N/D") -> str: if value is None: return fallback if isinstance(value, (str, int, float, bool)): text = str(value).strip() return text if text else fallback for attr in ("label", "name", "code", "value"): if hasattr(value, attr): v = getattr(value, attr) if v not in (None, ""): return str(v) raw = getattr(value, "raw_data", None) if isinstance(raw, dict): for key in ("label", "name", "code", "value"): v = raw.get(key) if v not in (None, ""): return str(v) return fallback def humanize_energy_label(value: Any) -> str: text = extract_display_value(value, fallback="N/D").strip() mapping = { "ELECTRICITY": "Elettrica", "ELEC": "Elettrica", "PETROL": "Benzina", "DIESEL": "Diesel", "HYBRID": "Ibrida", "PLUGIN_HYBRID": "Ibrida plug-in", } return mapping.get(text.upper(), text) def prettify_generic_status(value: Any) -> str: raw = str(value).strip().lower() mapping = { "locked": "Chiusa", "unlocked": "Aperta", "closed": "Chiusa", "open": "Aperta", "yes": "Sì", "no": "No", "true": "Sì", "false": "No", "1": "Sì", "0": "No", "none": "N/D", "n/d": "N/D", "": "N/D", } return mapping.get(raw, str(value) if value not in (None, "") else "N/D") def bool_like(value: Any) -> bool: try: return float(value) > 0 except (ValueError, TypeError): pass return str(value).strip().lower() in { "1", "1.0", "true", "yes", "on", "plugged", "connected", "locked", "charging", "charge_in_progress", } def format_datetime(value: Any, fallback: str = "N/D") -> str: if value in (None, "", "N/D"): return fallback try: ts = pd.to_datetime(value, utc=True, errors="coerce") if pd.isna(ts): return str(value) return ts.tz_convert("Europe/Rome").tz_localize(None).strftime("%d/%m/%Y %H:%M") except Exception: return str(value) def format_number( value: Any, suffix: str = "", fallback: str = "N/D", decimals: int = 0, ) -> str: if value in (None, "", "N/D"): return fallback try: number = float(value) if decimals == 0: return f"{int(round(number))}{suffix}" return f"{number:.{decimals}f}{suffix}" except Exception: return f"{value}{suffix}" def normalize_charge_mode(value: Any) -> str: raw = str(value).strip().lower() if raw in {"always", "always_charging", "always_schedule"}: return "Sempre" if raw in {"scheduled", "schedule_mode", "schedule"}: return "Programmata" return str(value) if value not in (None, "") else "N/D" # ─── Lock anti-race-condition per refresh ──────────────────────────────────── def is_refreshing() -> bool: """True se un aggiornamento dati è già in corso.""" return st.session_state.get("_refreshing", False) def set_refreshing(value: bool) -> None: st.session_state["_refreshing"] = value # ─── Persistenza costi ricarica ─────────────────────────────────────────────── import json, os COST_FILE = "saved_costs.json" def load_saved_costs() -> dict[str, float]: """ Carica i prezzi personalizzati (€/kWh) salvati per sessione. Formato: {"Data e Ora_epoch": prezzo} """ if not os.path.exists(COST_FILE): return {} try: with open(COST_FILE, encoding="utf-8") as f: return json.load(f) except Exception: return {} def save_costs_to_disk(costs: dict[str, float]) -> None: try: with open(COST_FILE, "w", encoding="utf-8") as f: json.dump(costs, f, indent=2) except Exception: pass # Silenzioso — non bloccare l'app per un file def merge_saved_costs(edited_df: pd.DataFrame, key_col: str = "Data e Ora") -> pd.DataFrame: """ Unisce i costi salvati con quelli appena editati. Usa la data come chiave. """ saved = load_saved_costs() if not saved: return edited_df for i, row in edited_df.iterrows(): ts = row.get(key_col) if ts and str(ts) in saved: edited_df.at[i, "Prezzo (€/kWh)"] = saved[str(ts)] return edited_df