"""Time helpers for crawler/admin code.

Operational timestamps are stored in naive DB DateTime columns, and production
uses Asia/Shanghai as the business timezone. These helpers make that convention
explicit at the boundaries.
"""
from __future__ import annotations

from datetime import datetime
from zoneinfo import ZoneInfo

CN_TZ = ZoneInfo("Asia/Shanghai")


def now_cn_naive() -> datetime:
    """Return current Asia/Shanghai wall-clock time for naive DB columns."""
    return datetime.now(CN_TZ).replace(tzinfo=None)


def iso_cn(dt: datetime | None) -> str | None:
    """Serialize a timestamp with an explicit Asia/Shanghai offset."""
    if dt is None:
        return None
    if dt.tzinfo is not None:
        return dt.astimezone(CN_TZ).isoformat()
    return dt.replace(tzinfo=CN_TZ).isoformat()


def epoch_iso_cn(ts: float | None) -> str | None:
    """Serialize a Unix epoch timestamp as Asia/Shanghai ISO text."""
    if ts is None:
        return None
    return datetime.fromtimestamp(ts, tz=CN_TZ).isoformat()


def epoch_db_dt_cn(ts: float | None) -> datetime | None:
    """Convert a Unix epoch to the naive Asia/Shanghai value stored in DB."""
    if ts is None:
        return None
    return datetime.fromtimestamp(ts, tz=CN_TZ).replace(tzinfo=None)
