import os
import logging
from typing import Iterable
import requests
from .supabase_service import get_client
from datetime import datetime

LOG_LEVEL = os.getenv("LOG_LEVEL", "INFO").upper()
logging.basicConfig(level=LOG_LEVEL, format="[%(levelname)s] %(message)s")
logger = logging.getLogger("telegram_sender")

SUBSCRIBERS_TABLE = "subscribers"

def _get_bot_token() -> str | None:
    """Fetch BOT_TOKEN on demand. If missing, returns None (skip send)."""
    t = (os.getenv("BOT_TOKEN") or "").strip()
    return t or None

def _api_url() -> str | None:
    tok = _get_bot_token()
    if not tok:
        return None
    return f"https://api.telegram.org/bot{tok}/sendMessage"

def _in_quiet_hours() -> bool:
    """Return True if current local time is within quiet hours.
    Format: QUIET_HOURS="22-07" (start-end, 24h). If unset/invalid -> False.
    """
    raw = (os.getenv("QUIET_HOURS") or "").strip()
    if not raw or "-" not in raw:
        return False
    try:
        start_s, end_s = [p.strip() for p in raw.split("-", 1)]
        sh = int(start_s)
        eh = int(end_s)
        now_h = datetime.now().hour
        if sh == eh:
            return False
        if sh < eh:
            # same day window, e.g., 22-23
            return sh <= now_h < eh
        # overnight window, e.g., 22-07
        return now_h >= sh or now_h < eh
    except Exception:
        return False

def get_all_subscribers(limit: int = 10000) -> list[int]:
    sb = get_client()
    res = sb.table(SUBSCRIBERS_TABLE).select("chat_id").limit(limit).execute()
    return [row["chat_id"] for row in (res.data or [])]

def _send_one(chat_id: int, html: str) -> bool:
    api = _api_url()
    if not api:
        # Graceful no-op when BOT_TOKEN is not set
        logger.info("BOT_TOKEN not set; skip Telegram send (chat_id=%s)", chat_id)
        return False
    try:
        payload = {
            "chat_id": chat_id,
            "text": html,
            "parse_mode": "HTML",
            "disable_web_page_preview": True,
        }
        if _in_quiet_hours():
            payload["disable_notification"] = True
        r = requests.post(
            api,
            json=payload,
            timeout=15,
        )
        ok = r.ok and r.json().get("ok", False)
        if not ok:
            logger.warning("send fail %s: %s", chat_id, r.text)
        return ok
    except Exception as e:
        logger.warning("send exception %s: %s", chat_id, e)
        return False

def send_html_to(chat_ids: Iterable[int], html: str) -> int:
    sent = 0
    for cid in chat_ids:
        if _send_one(cid, html):
            sent += 1
    return sent

def broadcast_html(html: str) -> int:
    subs = get_all_subscribers()
    if not subs:
        logger.info("no subscribers")
        return 0
    return send_html_to(subs, html)
