from __future__ import annotations

from datetime import datetime, time
from pathlib import Path
from zoneinfo import ZoneInfo

import polars as pl

from .files import TRADE_DAYS

SHANGHAI_TZ = ZoneInfo("Asia/Shanghai")
_AM_START = time(9, 15)
_AM_END = time(11, 30)
_PM_START = time(13, 0)
_PM_END = time(15, 5)  # 延后至 15:05，确保抓到收盘集合竞价最终成交价

_trade_days_cache: set[str] | None = None
_trade_days_mtime_ns: int | None = None


def _load_trade_days() -> set[str]:
    global _trade_days_cache, _trade_days_mtime_ns

    path: Path = TRADE_DAYS.get_local_path()
    if not path.exists():
        return set()

    current_mtime = path.stat().st_mtime_ns
    if _trade_days_cache is not None and _trade_days_mtime_ns == current_mtime:
        return _trade_days_cache

    df = (
        TRADE_DAYS.output_lazyframe()
        .filter(pl.col("is_trade_day") == True)
        .select(pl.col("date").cast(pl.String))
        .collect()
    )
    trade_days = set(df["date"].to_list())
    _trade_days_cache = trade_days
    _trade_days_mtime_ns = current_mtime
    return trade_days


def is_trading_time() -> bool:
    """
    是否在 A 股交易时间:
    1. 今天是交易日
    2. 当前时间在 09:15-11:30 或 13:00-15:05
       注：下午收盘延至 15:05，确保抓到 15:00 集合竞价最终成交价
    """
    now = datetime.now(SHANGHAI_TZ)
    today = now.date().isoformat()
    if today not in _load_trade_days():
        return False

    now_time = now.time()
    in_am = _AM_START <= now_time <= _AM_END
    in_pm = _PM_START <= now_time <= _PM_END
    return in_am or in_pm
