# engine/market.py
from datetime import datetime, time as dtime, timedelta
import pytz

_MARKET_TZ = pytz.timezone("Asia/Kolkata")
_OPEN_T = dtime(9, 15)
_CLOSE_T = dtime(15, 30)

def _as_market_tz(value: datetime) -> datetime:
    if value.tzinfo is None:
        return _MARKET_TZ.localize(value)
    return value.astimezone(_MARKET_TZ)

def is_market_open(now: datetime) -> bool:
    now = _as_market_tz(now)
    return now.weekday() < 5 and _OPEN_T <= now.time() <= _CLOSE_T

def india_market_status():
    now = datetime.now(_MARKET_TZ)

    return is_market_open(now), now

def next_market_open_after(value: datetime) -> datetime:
    current = _as_market_tz(value)
    while current.weekday() >= 5:
        current = current + timedelta(days=1)
        current = current.replace(hour=_OPEN_T.hour, minute=_OPEN_T.minute, second=0, microsecond=0)
    if current.time() < _OPEN_T:
        return current.replace(hour=_OPEN_T.hour, minute=_OPEN_T.minute, second=0, microsecond=0)
    if current.time() > _CLOSE_T:
        current = current + timedelta(days=1)
        while current.weekday() >= 5:
            current = current + timedelta(days=1)
        return current.replace(hour=_OPEN_T.hour, minute=_OPEN_T.minute, second=0, microsecond=0)
    return current

def align_to_market_open(value: datetime) -> datetime:
    current = _as_market_tz(value)
    aligned = current if is_market_open(current) else next_market_open_after(current)
    if value.tzinfo is None:
        return aligned.replace(tzinfo=None)
    return aligned
