"""
Gui thong bao qua Telegram Bot API.
Neu chua cau hinh token/channel, cac ham nay se bi bo qua im lang.
"""
from __future__ import annotations

import json
import urllib.request


def _send(token: str, chat_id: str, text: str) -> None:
    if not token or not chat_id:
        return
    url = f"https://api.telegram.org/bot{token}/sendMessage"
    payload = json.dumps({
        "chat_id": chat_id,
        "text": text,
        "parse_mode": "HTML",
    }).encode()
    req = urllib.request.Request(
        url, data=payload, headers={"Content-Type": "application/json"}
    )
    try:
        urllib.request.urlopen(req, timeout=10)
    except Exception as e:
        print(f"  [telegram] Khong gui duoc thong bao: {e}")


def _token_channel(settings: dict) -> tuple[str, str]:
    return settings.get("telegram_token", ""), settings.get("telegram_channel", "")


def notify_product_done(settings: dict, profile_alias: str, product_name: str) -> None:
    t, c = _token_channel(settings)
    _send(t, c,
          f"<b>Hoan thanh san pham</b>\n"
          f"San pham: {product_name}\n"
          f"Profile: {profile_alias}")


def notify_product_failed(
    settings: dict, profile_alias: str, product_name: str, error: str
) -> None:
    t, c = _token_channel(settings)
    _send(t, c,
          f"<b>Loi san pham</b>\n"
          f"San pham: {product_name}\n"
          f"Profile: {profile_alias}\n"
          f"Loi: {error[:200]}")


def notify_profile_done(
    settings: dict, profile_alias: str, done: int, failed: int
) -> None:
    t, c = _token_channel(settings)
    _send(t, c,
          f"<b>Profile hoan thanh</b>\n"
          f"Profile: {profile_alias}\n"
          f"Thanh cong: {done}  |  Loi: {failed}")


def notify_profile_limit_reached(settings: dict, profile_alias: str) -> None:
    """Thong bao profile da dat gioi han tao video trong ngay; da tat profile, tiep tuc profile khac."""
    t, c = _token_channel(settings)
    _send(t, c,
          f"<b>Gioi han video/ngay</b>\n"
          f"Chrome profile <b>{profile_alias}</b> da tao toi da video trong ngay hom nay.\n"
          f"Da tat profile nay, tiep tuc voi profile khac (neu co).")


def notify_all_done(settings: dict, total_done: int, total_failed: int) -> None:
    t, c = _token_channel(settings)
    _send(t, c,
          f"<b>Tat ca hoan thanh!</b>\n"
          f"Thanh cong: {total_done}\n"
          f"Loi: {total_failed}\n"
          f"Tong: {total_done + total_failed}")
