# -*- coding: utf-8 -*-
"""SU_KIEN.PY — dòng sự kiện chính thức cho bản tin (03/10/2026).

Chủ dự án chọn nguồn: lịch kinh tế MT5 (lich_tin.py) + NGUỒN CHÍNH THỨC CÔNG KHAI. Ở đây là Cục Dự trữ Liên bang Mỹ:
  - thông cáo chính sách tiền tệ (FOMC statement, dự phóng kinh tế, biên bản…) — feeds/press_monetary.xml
  - bài phát biểu của lãnh đạo Fed — feeds/speeches.xml
Chỉ lấy SỰ KIỆN (tiêu đề, người nói, giờ, link), không chép nội dung bài. Nguồn RSS chỉ giữ vài chục mục gần nhất nên
mỗi lần tải được GỘP vào kho tệp (_du_lieu/su_kien_fed.json, không vào git) để có lịch sử cho tổng kết tuần / tháng.
(Bộ Tài chính Mỹ, BLS chặn máy chủ — số liệu BLS đã có trong lịch MT5.)
"""
from __future__ import annotations

import json
import os
import xml.etree.ElementTree as ET
from datetime import datetime, timedelta, timezone
from email.utils import parsedate_to_datetime
from typing import Any, Dict, List

NGUON = {'chinh_sach': 'https://www.federalreserve.gov/feeds/press_monetary.xml',
         'phat_bieu': 'https://www.federalreserve.gov/feeds/speeches.xml'}
TEP = os.path.join(os.path.dirname(os.path.abspath(__file__)), '_du_lieu', 'su_kien_fed.json')


def doc_rss(van_ban: str, loai: str) -> List[Dict[str, Any]]:
    ra = []
    for it in ET.fromstring(van_ban).iter('item'):
        tieu_de = (it.findtext('title') or '').strip()
        link = (it.findtext('link') or '').strip()
        try:
            t = parsedate_to_datetime(it.findtext('pubDate') or '').astimezone(timezone.utc).replace(tzinfo=None)
        except (TypeError, ValueError):
            continue
        if not tieu_de or not link:
            continue
        x = {'loai': loai, 'tieu_de': tieu_de, 'link': link, 't_utc': t.strftime('%Y-%m-%d %H:%M')}
        if loai == 'phat_bieu' and ',' in tieu_de:          # "Waller, The Data Version of …"
            x['nguoi'], x['chu_de'] = [p.strip() for p in tieu_de.split(',', 1)]
        ra.append(x)
    return ra


def cap_nhat(_lay=None) -> int:
    """Tải các nguồn, gộp vào kho. Trả số mục trong kho. Lỗi mạng: giữ kho cũ."""
    if _lay is None:
        import httpx
        _lay = lambda u: httpx.get(u, timeout=20, headers={'User-Agent': 'TradingAuto ban tin'}).text  # noqa: E731
    kho = {x['link']: x for x in doc_kho()}
    for loai, url in NGUON.items():
        try:
            for x in doc_rss(_lay(url), loai):
                kho[x['link']] = x
        except Exception:  # noqa: BLE001
            continue
    os.makedirs(os.path.dirname(TEP), exist_ok=True)
    ds = sorted(kho.values(), key=lambda x: x['t_utc'])
    json.dump(ds, open(TEP, 'w', encoding='utf-8'), ensure_ascii=False, indent=0)
    return len(ds)


def doc_kho() -> List[Dict[str, Any]]:
    try:
        return json.load(open(TEP, encoding='utf-8'))
    except (OSError, ValueError):
        return []


def trong(tu_vn: datetime, den_vn: datetime, kho: List[Dict[str, Any]] = None) -> List[Dict[str, Any]]:
    """Sự kiện Fed có giờ (VN) trong [tu_vn, den_vn)."""
    ra = []
    for x in (doc_kho() if kho is None else kho):
        vn = datetime.strptime(x['t_utc'], '%Y-%m-%d %H:%M') + timedelta(hours=7)
        if tu_vn <= vn < den_vn:
            y = {'luc': vn.strftime('%d/%m %H:%M'), 'loai': 'Thông cáo chính sách tiền tệ của Fed' if x['loai'] == 'chinh_sach'
                 else 'Phát biểu của lãnh đạo Fed', 'tieu_de_goc': x['tieu_de']}
            if x.get('nguoi'):
                y['nguoi'] = x['nguoi']
            ra.append(y)
    return ra


if __name__ == '__main__':
    mau = ('<rss><channel><item><title>Waller, The U.S. Economy</title><link>https://f/a</link>'
           '<pubDate>Wed, 01 Oct 2026 14:00:00 GMT</pubDate></item><item><title>x</title></item></channel></rss>')
    d = doc_rss(mau, 'phat_bieu')
    assert d == [{'loai': 'phat_bieu', 'tieu_de': 'Waller, The U.S. Economy', 'link': 'https://f/a',
                  't_utc': '2026-10-01 14:00', 'nguoi': 'Waller', 'chu_de': 'The U.S. Economy'}], d
    r = trong(datetime(2026, 10, 1, 7), datetime(2026, 10, 2, 7), d)
    assert r[0]['luc'] == '01/10 21:00' and r[0]['nguoi'] == 'Waller'
    print('TỰ KIỂM ban_tin/su_kien.py QUA.')
