"""
Intraday VWAP (cumulative from UTC midnight) — port fedele da V15.

Falls back to "VWAP over the whole DataFrame" when:
  - no timestamp column / DatetimeIndex available
  - fewer than 3 bars since UTC midnight (session just started)

Returns (vwap, deviation_pct) where deviation_pct = (close - vwap)/vwap * 100.
"""

from __future__ import annotations

from datetime import datetime, timezone

import pandas as pd


def _vwap_simple(df: pd.DataFrame) -> tuple[float, float]:
    """Fallback: VWAP over the whole DF (no session filter)."""
    vol_col = "volume" if "volume" in df.columns else "tick_volume"
    if vol_col not in df.columns or df.empty:
        return 0.0, 0.0
    typical = (df["high"] + df["low"] + df["close"]) / 3
    cum_tp_vol = (typical * df[vol_col]).cumsum()
    cum_vol = df[vol_col].cumsum()
    vwap = float(cum_tp_vol.iloc[-1] / (cum_vol.iloc[-1] + 1e-9))
    last_close = float(df["close"].iloc[-1])
    deviation_pct = (last_close - vwap) / (vwap + 1e-9) * 100
    return round(vwap, 5), round(deviation_pct, 3)


def calc_vwap_intraday(df5: pd.DataFrame) -> tuple[float, float]:
    """
    Cumulative VWAP from UTC midnight of the current day.

    Args:
        df5: M5 OHLCV DataFrame with `time`/`timestamp`/`datetime` column
             OR a DatetimeIndex; volume column required.

    Returns:
        (vwap, deviation_pct). (0.0, 0.0) if computation impossible.
    """
    if df5.empty:
        return 0.0, 0.0

    ts_col = None
    for c in ("timestamp", "time", "datetime"):
        if c in df5.columns:
            ts_col = c
            break

    if ts_col is None:
        if isinstance(df5.index, pd.DatetimeIndex):
            df = df5.copy()
            df["_ts"] = df.index
            ts_col = "_ts"
        else:
            return _vwap_simple(df5)

    today_start = datetime.now(timezone.utc).replace(
        hour=0, minute=0, second=0, microsecond=0
    )

    df = df5.copy()
    if not pd.api.types.is_datetime64_any_dtype(df[ts_col]):
        try:
            df[ts_col] = pd.to_datetime(df[ts_col], utc=True)
        except Exception:
            return _vwap_simple(df5)
    else:
        if df[ts_col].dt.tz is None:
            df[ts_col] = df[ts_col].dt.tz_localize("UTC")

    df_today = df[df[ts_col] >= today_start].copy()
    if len(df_today) < 3:
        return _vwap_simple(df5)

    vol_col = "volume" if "volume" in df_today.columns else "tick_volume"
    if vol_col not in df_today.columns:
        return _vwap_simple(df5)

    typical = (df_today["high"] + df_today["low"] + df_today["close"]) / 3
    cum_tp_vol = (typical * df_today[vol_col]).cumsum()
    cum_vol = df_today[vol_col].cumsum()
    vwap = float(cum_tp_vol.iloc[-1] / (cum_vol.iloc[-1] + 1e-9))
    last_close = float(df_today["close"].iloc[-1])
    deviation_pct = (last_close - vwap) / (vwap + 1e-9) * 100
    return round(vwap, 5), round(deviation_pct, 3)
