# -*- coding: utf-8 -*-
"""DIEN_TAP.PY — diễn tập bản tin trên số liệu THẬT các ngày đã qua, KHÔNG đăng gì (02/10/2026).

Chủ dự án: "tốt nhất là diễn tập trước thử vài nội dung để tôi đánh giá, bạn tạo sẵn vài nội dung có thể xảy ra vào
các ngày vừa qua và tôi đánh giá là được". Mỗi buổi sáng: bài sáng bản 1 (lời thường) + bản 2 (kèm chỉ số), bài kết quả
bot, và BÁO CÁO TỰ CHẤM riêng cho chủ (không đăng). Kết quả: <thu_muc>/ket_qua.json + ảnh PNG.

Lịch (chủ dự án 03/10/2026):
  bài sáng  — T2–T6 bản tin ngày 11 phần ('A'; ngày giao dịch đầu tháng thay bằng tầm nhìn tháng 'M'),
              T7 kết phiên thứ Sáu ('S'), CN tổng kết + tầm nhìn tuần ('T');
  kết quả bot — T3–T7 kết quả ngày hôm trước ('B'), CN cả tuần ('D'), T2 không có;
  tự chấm  — chỉ gửi riêng chủ (bao_cao_rieng), không vào bài.

Dùng:  python -m ban_tin.dien_tap <thu_muc> <goi.json> 2026-09-28 2026-09-29 ...
       python -m ban_tin.dien_tap --chi-de-bai <thu_muc> <goi.json> <ngày>…   (chỉ đề bài, không gọi mô hình)
"""
from __future__ import annotations

import json
import os
import sys
import time
from datetime import date, timedelta
from typing import Optional

from ban_tin import bao_cao_rieng
from ban_tin.bieu_do import chup, html_bieu_do, html_bieu_do_thang, html_bieu_do_tuan, html_the_ket_qua
from ban_tin.ket_qua_bot import so_lieu_bot, so_lieu_bot_tuan, them_tam_tinh
from ban_tin.phan_tich import ket_phien_thu_sau, ngay_dau_thang, so_lieu_sang, tam_nhin_thang, tong_ket_tuan
from ban_tin.viet import (cau_dan_a, cau_dan_b, cau_dan_d, cau_dan_sau, cau_dan_thang, cau_dan_tuan, de_bai, du_kien_a,
                          du_kien_b, du_kien_d, du_kien_sau, du_kien_thang, du_kien_tuan, viet)


def loai_bai_sang(ngay: date) -> str:
    if ngay.weekday() == 6:
        return 'T'
    if ngay.weekday() == 5:
        return 'S'
    return 'M' if ngay_dau_thang(ngay) else 'A'


def _lay(dem: dict, khoa: str, ham):
    if khoa not in dem:
        dem[khoa] = ham()
    return dem[khoa]


def bai_sang(goi: dict, ngay: date, chi_so: bool, he_thong: dict, dem: dict) -> tuple:
    """(câu dẫn, dữ kiện, loại, trang HTML biểu đồ) cho bài buổi sáng."""
    loai = loai_bai_sang(ngay)
    if loai == 'M':
        m = _lay(dem, 'M', lambda: tam_nhin_thang(goi, ngay))
        return cau_dan_thang(chi_so), du_kien_thang(m, chi_so, he_thong), loai, html_bieu_do_thang(m, chi_so)
    if loai == 'T':
        t = _lay(dem, 'T', lambda: tong_ket_tuan(goi, ngay))
        return cau_dan_tuan(chi_so), du_kien_tuan(t, chi_so, he_thong), loai, html_bieu_do_tuan(t, chi_so)
    if loai == 'S':
        sl = _lay(dem, 'S', lambda: ket_phien_thu_sau(goi, ngay))
        return cau_dan_sau(chi_so), du_kien_sau(sl, chi_so, he_thong), loai, html_bieu_do(sl, chi_so)
    sl = _lay(dem, 'A', lambda: so_lieu_sang(goi, ngay))
    return cau_dan_a(chi_so), du_kien_a(sl, chi_so, he_thong), loai, html_bieu_do(sl, chi_so)


def bai_ket_qua(goi: dict, ngay: date) -> Optional[tuple]:
    """(câu dẫn, dữ kiện, loại, trang HTML thẻ, kq) cho bài kết quả bot; thứ Hai không có."""
    if ngay.weekday() == 0:
        return None
    if ngay.weekday() == 6:
        kq = so_lieu_bot_tuan(ngay)
        sl = so_lieu_sang(goi, ngay - timedelta(days=1), tu_cham=False)      # sáng thứ Bảy: hom_qua = nến thứ Sáu
        them_tam_tinh(kq, sl['hom_qua']['dong'])
        dk = du_kien_d(kq)
        return cau_dan_d(), dk, 'D', html_the_ket_qua(kq), kq
    kq = so_lieu_bot(ngay)
    sl = so_lieu_sang(goi, ngay, tu_cham=False)
    a = du_kien_a(sl, False)
    tt = (a.get('p11_he_thong_hom_nay') or {}).get('trang_thai_thi_truong_theo_he_thong')
    them_tam_tinh(kq, sl['hom_qua']['dong'])
    dk = du_kien_b(kq, {'trang_thai': tt, 'phien': a['phien_truoc']})
    return cau_dan_b(), dk, 'B', html_the_ket_qua(kq), kq


def bao_cao(goi: dict, ngay: date, dem: dict) -> Optional[str]:
    """Báo cáo tự chấm gửi riêng chủ: T3–T7 chấm bản tin hôm trước, CN tổng hợp cả tuần, ngày đầu tháng thêm cả tháng.
    Thứ Hai không gửi (bản thứ Sáu đã chấm sáng thứ Bảy, tuần đã tổng hợp Chủ nhật)."""
    loai = loai_bai_sang(ngay)
    if loai == 'T':
        t = _lay(dem, 'T', lambda: tong_ket_tuan(goi, ngay))
        return bao_cao_rieng.van_ban_tong_hop(t['cham'], f"tuần {t['tuan_tu'][8:]}/{t['tuan_tu'][5:7]}–{t['tuan_den'][8:]}/{t['tuan_den'][5:7]}")
    if ngay.weekday() == 0:
        return None
    sl = (_lay(dem, 'S', lambda: ket_phien_thu_sau(goi, ngay)) if loai == 'S'
          else _lay(dem, 'A', lambda: so_lieu_sang(goi, ngay)))          # ngày đầu tháng: vẫn chấm bản tin hôm trước
    phan = [bao_cao_rieng.van_ban_ngay(sl['tu_cham'])] if sl.get('tu_cham') else []
    if loai == 'M':
        m = _lay(dem, 'M', lambda: tam_nhin_thang(goi, ngay))
        phan.append(bao_cao_rieng.van_ban_tong_hop(m['cham'], f"tháng {m['thang_truoc']}"))
    return '\n\n'.join(phan) or None


def chuan_bi(thu_muc: str, goi: dict, ngay_ds) -> list:
    """Chỉ tính số liệu + vẽ ảnh + soạn ĐỀ BÀI (de_bai.json) + báo cáo tự chấm (bao_cao.json), không gọi mô hình.
    Bài do agent viết rồi ghép bằng viet.ghep."""
    os.makedirs(thu_muc, exist_ok=True)
    ds, bc = [], {}
    for ngay in ngay_ds:
        t0 = time.time()
        dem: dict = {}
        kqb = bai_ket_qua(goi, ngay)
        he_thong = {'viptrend_mo': (kqb[4] if kqb else so_lieu_bot(ngay))['viptrend_mo']}
        for chi_so in (False, True):
            k = 'A2' if chi_so else 'A1'
            cd, dk, loai, trang = bai_sang(goi, ngay, chi_so, he_thong, dem)
            ten = f'{ngay.isoformat()}_{k}.png'
            open(os.path.join(thu_muc, ten), 'wb').write(chup(trang, 1200, 675))
            ds.append({'ma': f'{ngay.isoformat()}_{k}', 'ngay': ngay.isoformat(), 'thu': ngay.weekday(), 'k': k,
                       'anh': ten, 'du_kien': dk, **de_bai(cd, dk, loai)})
        if kqb:
            cd, dk, loai, trang, _kq = kqb
            ten = f'{ngay.isoformat()}_B.png'
            open(os.path.join(thu_muc, ten), 'wb').write(chup(trang, 1200))
            ds.append({'ma': f'{ngay.isoformat()}_B', 'ngay': ngay.isoformat(), 'thu': ngay.weekday(), 'k': 'B',
                       'anh': ten, 'du_kien': dk, **de_bai(cd, dk, loai)})
        bc[ngay.isoformat()] = bao_cao(goi, ngay, dem)
        print(ngay, loai_bai_sang(ngay), 'xong', round(time.time() - t0), 'giây', flush=True)
        json.dump(ds, open(os.path.join(thu_muc, 'de_bai.json'), 'w', encoding='utf-8'), ensure_ascii=False, indent=1)
        json.dump(bc, open(os.path.join(thu_muc, 'bao_cao.json'), 'w', encoding='utf-8'), ensure_ascii=False, indent=1)
    return ds


def chay(thu_muc: str, goi: dict, ngay_ds) -> list:
    """Có gọi mô hình. Chạy lại được: bản nào trong ket_qua.json cũ đã đạt (không lỗi, có ảnh) thì giữ."""
    os.makedirs(thu_muc, exist_ok=True)
    tep = os.path.join(thu_muc, 'ket_qua.json')
    cu = {m['ngay']: m for m in json.load(open(tep, encoding='utf-8'))} if os.path.isfile(tep) else {}

    def _dat(m, k):
        return bool(m and k in m and not m[k].get('loi') and os.path.isfile(os.path.join(thu_muc, m[k].get('anh', '?'))))
    ra = []
    for ngay in ngay_ds:
        t0 = time.time()
        dem: dict = {}
        kqb = bai_ket_qua(goi, ngay)
        he_thong = {'viptrend_mo': (kqb[4] if kqb else so_lieu_bot(ngay))['viptrend_mo']}
        m_cu = cu.get(ngay.isoformat())
        muc = {'ngay': ngay.isoformat(), 'thu': ngay.weekday(), 'bao_cao': bao_cao(goi, ngay, dem)}
        for k in ('A1', 'A2', 'B'):
            if _dat(m_cu, k):
                muc[k] = m_cu[k]
        for chi_so in (False, True):
            k = 'A2' if chi_so else 'A1'
            if k in muc:
                continue
            cd, dk, loai, trang = bai_sang(goi, ngay, chi_so, he_thong, dem)
            muc[k] = dict(viet(cd, dk, loai), du_kien=dk, loai=loai)
            ten = f'{ngay.isoformat()}_{k}.png'
            open(os.path.join(thu_muc, ten), 'wb').write(chup(trang, 1200, 675))
            muc[k]['anh'] = ten
        if kqb and 'B' not in muc:
            cd, dk, loai, trang, _kq = kqb
            muc['B'] = dict(viet(cd, dk, loai), du_kien=dk, loai=loai)
            ten = f'{ngay.isoformat()}_B.png'
            open(os.path.join(thu_muc, ten), 'wb').write(chup(trang, 1200))
            muc['B']['anh'] = ten
        ra.append(muc)
        print(ngay, 'xong', round(time.time() - t0), 'giây', flush=True)
        json.dump(ra, open(tep, 'w', encoding='utf-8'), ensure_ascii=False, indent=1)
    return ra


if __name__ == '__main__':
    chi_de = '--chi-de-bai' in sys.argv
    a = [x for x in sys.argv[1:] if x != '--chi-de-bai']
    goi = json.load(open(a[1], encoding='utf-8'))
    (chuan_bi if chi_de else chay)(a[0], goi, [date.fromisoformat(x) for x in a[2:]])
