"""A small Telegram bot: prayer times for Kuala Terengganu.

Commands:
  /start  what the bot does
  /today  today's prayer times
  /next   the next prayer and how long until it

Times come from JAKIM's e-Solat (zone TRG01, Kuala Terengganu).
The bot talks to Telegram with plain HTTPS long polling (no framework).
"""

import os
import time
from datetime import date, datetime, timedelta
from pathlib import Path
from zoneinfo import ZoneInfo

import requests

ZONE = "TRG01"  # Kuala Terengganu in JAKIM's zone list
TZ = ZoneInfo("Asia/Kuala_Lumpur")
ESOLAT_URL = "https://www.e-solat.gov.my/index.php"
API_BASE = os.environ.get("TELEGRAM_API_BASE", "https://api.telegram.org")
ENV_FILE = Path(__file__).with_name(".env")  # ~/bot/.env, next to this file

# (key in the e-Solat reply, name we show). Syuruk is sunrise, not a prayer.
TIMES = [
    ("fajr", "Subuh"),
    ("syuruk", "Syuruk"),
    ("dhuhr", "Zohor"),
    ("asr", "Asar"),
    ("maghrib", "Maghrib"),
    ("isha", "Isyak"),
]
PRAYERS = [t for t in TIMES if t[0] != "syuruk"]

# e-Solat writes dates in Malay, like "01-Dis-2026".
MONTHS = {"Jan": 1, "Feb": 2, "Mac": 3, "Apr": 4, "Mei": 5, "Jun": 6,
          "Jul": 7, "Ogos": 8, "Sep": 9, "Okt": 10, "Nov": 11, "Dis": 12}


def log(msg):
    print(datetime.now(TZ).strftime("%Y-%m-%d %H:%M:%S"), msg, flush=True)


# ---------- prayer times ----------

def parse_esolat(data):
    """Turn an e-Solat reply into {date: {"fajr": datetime, ...}}."""
    days = {}
    for row in data["prayerTime"]:
        d, m, y = row["date"].split("-")
        day = date(int(y), MONTHS[m], int(d))
        days[day] = {}
        for key, _ in TIMES:
            hh, mm, _ss = row[key].split(":")
            days[day][key] = datetime(day.year, day.month, day.day,
                                      int(hh), int(mm), tzinfo=TZ)
    return days


_cache = {}  # date -> times, filled once a day


def times_for(day):
    """Times for one day. Fetches a week at a time, so /next works after Isyak."""
    if day not in _cache:
        log(f"fetching e-Solat week for {ZONE}")
        r = requests.get(ESOLAT_URL, timeout=20, params={
            "r": "esolatApi/TakwimSolat", "period": "week", "zone": ZONE})
        r.raise_for_status()
        _cache.clear()
        _cache.update(parse_esolat(r.json()))
    return _cache[day]


def next_prayer(now, today, tomorrow):
    """Return (name, time) of the first prayer after `now`."""
    for key, name in PRAYERS:
        if today[key] > now:
            return name, today[key]
    return "Subuh", tomorrow["fajr"]


def until(delta):
    """timedelta -> '2 h 15 min'."""
    minutes = int(delta.total_seconds() // 60)
    h, m = divmod(minutes, 60)
    return f"{h} h {m} min" if h else f"{m} min"


def today_text(now):
    t = times_for(now.date())
    lines = [f"Prayer times, Kuala Terengganu, {now:%a %d %b %Y}"]
    for key, name in TIMES:
        lines.append(f"{name}: {t[key]:%H:%M}")
    return "\n".join(lines)


def next_text(now):
    name, at = next_prayer(now, times_for(now.date()),
                           times_for(now.date() + timedelta(days=1)))
    return f"Next: {name} at {at:%H:%M}, in {until(at - now)}."


START_TEXT = ("Assalamualaikum! I send prayer times for Kuala Terengganu "
              "(JAKIM e-Solat, zone TRG01).\n"
              "/today - today's times\n"
              "/next - the next prayer and how long until it")


def reply_for(text, now):
    cmd = text.split()[0].split("@")[0].lower() if text.strip() else ""
    if cmd == "/today":
        return today_text(now)
    if cmd == "/next":
        return next_text(now)
    return START_TEXT  # /start, and anything else


# ---------- Telegram ----------

def read_token():
    """TELEGRAM_TOKEN from the environment, or from ~/bot/.env."""
    token = os.environ.get("TELEGRAM_TOKEN", "").strip()
    if token:
        return token
    try:
        for line in ENV_FILE.read_text().splitlines():
            if line.startswith("TELEGRAM_TOKEN="):
                return line.split("=", 1)[1].strip().strip('"\'')
    except FileNotFoundError:
        pass
    return ""


def call(token, method, **params):
    r = requests.post(f"{API_BASE}/bot{token}/{method}", json=params, timeout=40)
    r.raise_for_status()
    return r.json()["result"]


def main():
    token = read_token()
    while not token:
        log("waiting for TELEGRAM_TOKEN in ~/bot/.env")
        time.sleep(30)
        token = read_token()

    log("bot started, long polling Telegram")
    offset = 0
    while True:
        try:
            updates = call(token, "getUpdates", offset=offset, timeout=30)
            for u in updates:
                offset = u["update_id"] + 1
                msg = u.get("message")
                if not msg or "text" not in msg:
                    continue
                try:
                    text = reply_for(msg["text"], datetime.now(TZ))
                except requests.RequestException:
                    text = "Sorry, I could not reach e-Solat just now. Try again soon."
                call(token, "sendMessage", chat_id=msg["chat"]["id"], text=text)
                log(f"chat {msg['chat']['id']}: {msg['text']!r} -> replied")
        except Exception as e:  # network blip, Telegram or e-Solat down
            log("error: " + str(e).replace(token, "***"))
            time.sleep(5)


if __name__ == "__main__":
    main()
