# -*- coding: utf-8 -*-
"""PHAT.PY — phát một bản tin đã viết (viet.py) lên các kênh (02/10/2026).

  - Telegram: nhóm công khai, CHỦ ĐỀ "Kênh tin tức" (cau_hinh_thong_bao.tele_chu_de, bắt bằng /id trong chủ đề);
    ảnh + chú thích (chú thích > 1024 ký tự thì ảnh trước, chữ sau).
  - Zalo: tài khoản phụ (kenh/zalo_cn.gui_nhom), nhóm truyền vào.
  - Fanpage: KHÔNG tự đăng ở đây — gửi THẺ DUYỆT (kenh/bai_dang.gui_duyet), chủ shop bấm ✅ mới lên Trang.
    (Luật tự đăng 8:00 của bản tin A thuộc phần lịch chạy, chưa làm.)
  - Website: ghi bảng ban_tin + ảnh vào public_html/assets/images/ban_tin/ -> /tin-tuc/<slug>.
    trang_thai 'nhap' = chỉ admin xem (bản thử).

Bản thử cho chủ dự án đánh giá:
  python -m ban_tin.phat thu <thu_muc_dien_tap> <yyyy-mm-dd> [--tele] [--zalo <id nhóm>] [--fb] [--web] [--chi A2 --chi B]
"""
from __future__ import annotations

import json
import os
import sys
from datetime import date, datetime
from typing import Any, Dict, List, Optional, Tuple

from congcu import csdl

_GOC_WEB = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..', '..', '..'))
THU_MUC_ANH = 'assets/images/ban_tin'
TIEN_TO_THU = '🧪 BẢN THỬ — chưa phải bản tin chính thức\n\n'
GIOI_HAN_CHU_THICH = 1024


def _public() -> str:
    for goc in ('public_html', 'public'):
        p = os.path.join(_GOC_WEB, goc)
        if os.path.isdir(p):
            return p
    raise FileNotFoundError('Không thấy thư mục web công khai')


# ---------------------------------------------------------------------
# TELEGRAM
# ---------------------------------------------------------------------

def tele_dich(ct) -> Tuple[str, str, Optional[int]]:
    """(token bot, chat nhóm, id chủ đề "Kênh tin tức")."""
    from kenh.phieu import _cau_hinh_tele
    token, _chat_chu = _cau_hinh_tele(ct)
    ct.execute("SELECT gia_tri FROM cau_hinh_thong_bao WHERE khoa = 'tele_chu_de'")
    try:
        cd = json.loads(str((ct.fetchone() or {}).get('gia_tri') or '{}'))
    except ValueError:
        cd = {}
    for chat, ds in cd.items():
        for tid, ten in (ds or {}).items():
            if 'tin tức' in str(ten).lower():
                return token, str(chat), int(tid)
    return token, '', None


def phat_tele(token: str, chat: str, chu_de: Optional[int], chu: str, anh: Optional[str]) -> Tuple[bool, str]:
    import httpx
    url = f'https://api.telegram.org/bot{token}/'
    co_so: Dict[str, Any] = {'chat_id': chat}
    if chu_de:
        co_so['message_thread_id'] = chu_de
    try:
        if anh:
            du = dict(co_so)
            if len(chu) <= GIOI_HAN_CHU_THICH:
                du['caption'] = chu
            with open(anh, 'rb') as f:
                j = httpx.post(url + 'sendPhoto', data=du, files={'photo': (os.path.basename(anh), f, 'image/png')},
                               timeout=60).json()
            if not j.get('ok'):
                return False, str(j.get('description') or j)[:300]
            if 'caption' in du:
                return True, ''
        j = httpx.post(url + 'sendMessage', json=dict(co_so, text=chu, disable_web_page_preview=True), timeout=30).json()
        return bool(j.get('ok')), '' if j.get('ok') else str(j.get('description') or j)[:300]
    except Exception as loi:  # noqa: BLE001
        return False, str(loi)[:300]


# ---------------------------------------------------------------------
# WEBSITE
# ---------------------------------------------------------------------

def slug(ngay: date, loai: str, ban: int, thu: bool = False) -> str:
    goc = {'A': 'ban-tin-vang', 'B': 'ket-qua-bot', 'T': 'tong-ket-tuan-vang', 'M': 'tam-nhin-thang-vang',
           'D': 'ket-qua-bot-tuan'}[loai]
    s = f"{goc}-{ngay.strftime('%d-%m-%Y')}" + (f'-ban-{ban}' if loai in ('A', 'T', 'M') and ban != 1 else '')
    return s + ('-thu' if thu else '')


def luu_web(ngay: date, loai: str, ban: int, web: Dict[str, str], anh: Optional[str], *, trang_thai: str = 'nhap',
            thu: bool = False, _lay_ket_noi=None) -> str:
    """Ghi (hoặc ghi đè cùng slug) bài web + chép ảnh. Trả đường dẫn /tin-tuc/<slug>."""
    s = slug(ngay, loai, ban, thu)
    duong_anh = ''
    if anh:
        thu_muc = os.path.join(_public(), THU_MUC_ANH)
        os.makedirs(thu_muc, exist_ok=True)
        with open(anh, 'rb') as f_vao, open(os.path.join(thu_muc, s + '.png'), 'wb') as f_ra:
            f_ra.write(f_vao.read())
        duong_anh = f'/{THU_MUC_ANH}/{s}.png'

    def _viec(ct):
        ct.execute("""INSERT INTO ban_tin (ngay, loai, ban, slug, tieu_de, mo_ta, noi_dung, anh, trang_thai, tao_luc, dang_luc)
                      VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, NOW(), IF(%s = 'cong_khai', NOW(), NULL))
                      ON DUPLICATE KEY UPDATE tieu_de = VALUES(tieu_de), mo_ta = VALUES(mo_ta), noi_dung = VALUES(noi_dung),
                        anh = VALUES(anh), trang_thai = VALUES(trang_thai)""",
                   (ngay.isoformat(), loai, ban, s, web['tieu_de'][:200], web['mo_ta'][:300], web['noi_dung'], duong_anh,
                    trang_thai, trang_thai))
    csdl.voi_ct(_lay_ket_noi, _viec)
    return f'/tin-tuc/{s}'


# ---------------------------------------------------------------------
# BẢN THỬ TỪ KẾT QUẢ DIỄN TẬP
# ---------------------------------------------------------------------

def thu(thu_muc: str, ngay: date, tele: bool, zalo_nhom: List[str], fb: bool, web: bool,
        chi: Optional[List[str]] = None) -> List[str]:
    ds = {m['ngay']: m for m in json.load(open(os.path.join(thu_muc, 'ket_qua.json'), encoding='utf-8'))}
    m = ds[ngay.isoformat()]
    bao = []
    token = chat = ''
    chu_de = None
    if tele:
        token, chat, chu_de = csdl.voi_ct(None, tele_dich)
        if not chat:
            bao.append('Telegram: chưa bắt được chủ đề "Kênh tin tức" (gõ /id trong chủ đề)')
            tele = False
    home = ''
    if zalo_nhom:
        from kenh import zalo_cn
        home = zalo_cn.cau_hinh().get('zl_home') or ''
        if not home:
            bao.append('Zalo: chưa đăng nhập tài khoản phụ')
            zalo_nhom = []
    ten_loai = {'A': 'Bản tin sáng', 'T': 'Tổng kết tuần', 'M': 'Tầm nhìn tháng', 'B': 'Kết quả bot'}
    for k in (chi or ('A1', 'A2', 'B')):
        b = m.get(k)
        if not b:
            continue
        loai = b.get('loai') or ('B' if k == 'B' else 'A')
        ban = 2 if k == 'A2' else 1
        ten = ten_loai[loai] + ({'A1': ' · Bản 1 lời thường', 'A2': ' · Bản 2 kèm chỉ số'}.get(k, ''))
        anh = os.path.join(thu_muc, b['anh']) if b.get('anh') else None
        dau = TIEN_TO_THU.replace('\n\n', f' ({ten}, số liệu sáng {ngay.strftime("%d/%m")})\n\n')
        if web:
            duong = luu_web(ngay, loai, ban, b['web'], anh, thu=True)
            bao.append(f'Web {k}: https://tradingauto.org{duong} (bản nháp, chỉ admin xem)')
        if tele:
            ok, loi = phat_tele(token, chat, chu_de, dau + b['tele'], anh)
            bao.append(f'Telegram {k}: ' + ('đã gửi' if ok else 'LỖI ' + loi))
        for g in zalo_nhom:
            from kenh import zalo_cn
            ok, loi = zalo_cn.gui_nhom(home, g, dau + b['zalo'], anh)
            bao.append(f'Zalo {k} -> {g}: ' + ('đã gửi' if ok else 'LỖI ' + str(loi)[:200]))
        if fb:
            from kenh.bai_dang import gui_duyet
            anh_url = f"https://tradingauto.org/{THU_MUC_ANH}/{slug(ngay, loai, ban, True)}.png" if (anh and web) else ''
            i = gui_duyet(b['fb'], chu_de=f'BẢN THỬ {ngay.strftime("%d/%m")} — {ten}', anh_url=anh_url,
                          nguon=f'ban_tin_thu:{ngay.isoformat()}:{k}')
            bao.append(f'Fanpage {k}: thẻ duyệt #{i} đã gửi Telegram (chưa đăng)')
    return bao


if __name__ == '__main__':
    if len(sys.argv) >= 4 and sys.argv[1] == 'thu':
        a = sys.argv[4:]
        zn = [a[i + 1] for i, x in enumerate(a) if x == '--zalo' and i + 1 < len(a)]
        chi = [a[i + 1] for i, x in enumerate(a) if x == '--chi' and i + 1 < len(a)] or None
        for dong in thu(sys.argv[2], date.fromisoformat(sys.argv[3]), '--tele' in a, zn, '--fb' in a, '--web' in a, chi):
            print(dong, flush=True)
    else:
        assert slug(date(2026, 10, 2), 'A', 1) == 'ban-tin-vang-02-10-2026'
        assert slug(date(2026, 10, 2), 'A', 2, True) == 'ban-tin-vang-02-10-2026-ban-2-thu'
        assert slug(date(2026, 10, 2), 'B', 1) == 'ket-qua-bot-02-10-2026'
        assert slug(date(2026, 10, 1), 'M', 2, True) == 'tam-nhin-thang-vang-01-10-2026-ban-2-thu'
        print('TỰ KIỂM ban_tin/phat.py QUA.')
