"""Session context helpers for 24/7 crypto trading."""
from __future__ import annotations

import time
from datetime import datetime, timezone

from .models import Candle


def session_context(ts: float | None = None, reset_hour_utc: int = 0) -> dict:
    now = datetime.fromtimestamp(ts if ts is not None else time.time(), tz=timezone.utc)
    hour = now.hour
    if now.weekday() >= 5:
        label = "weekend"
        quality = "thin"
    elif 0 <= hour < 7:
        label = "asia"
        quality = "thin"
    elif 7 <= hour < 12:
        label = "europe"
        quality = "normal"
    elif 12 <= hour < 21:
        label = "us"
        quality = "high"
    else:
        label = "late_us"
        quality = "normal"

    reset_hour_utc = int(reset_hour_utc) % 24
    session_date = now.date()
    if hour < reset_hour_utc:
        session_date = datetime.fromtimestamp(now.timestamp() - 86400, tz=timezone.utc).date()

    return {
        "label": label,
        "quality": quality,
        "utc_hour": hour,
        "weekday": now.weekday(),
        "session_date": session_date.isoformat(),
        "reset_hour_utc": reset_hour_utc,
    }


def filter_session_candles(candles: list[Candle], session: dict) -> list[Candle]:
    """Keep candles from the current UTC session for VWAP/volume profile."""
    if not candles:
        return candles
    try:
        reset_hour = int(session.get("reset_hour_utc", 0)) % 24
        session_date = datetime.fromisoformat(str(session.get("session_date"))).date()
    except Exception:
        return candles
    filtered = []
    for candle in candles:
        dt = datetime.fromtimestamp(candle.ts / 1000, tz=timezone.utc)
        candle_session_date = dt.date()
        if dt.hour < reset_hour:
            candle_session_date = datetime.fromtimestamp(dt.timestamp() - 86400, tz=timezone.utc).date()
        if candle_session_date == session_date:
            filtered.append(candle)
    return filtered or candles
