# -*- coding: utf-8 -*-
"""Trích 22 mục QC (Lộc + Trí) trong 2 tuần 26/09–09/10/2026 → JSON + bản tóm tắt gọn để viết báo cáo HTML.
Xuất: <DICH>/_trich_xuat_2tuan.json  và in digest gọn (tiêu đề, heading con, dòng kết luận có số liệu)."""
import argparse, datetime, json, os, re, sys

GOC = r'C:\Claw 2\QC'
TEP = [('Locqc.md', 'Lộc'), ('Tri qc.md', 'Trí')]

# --- khoảng ngày truyền được từ dòng lệnh (mặc định 26/09/2026 → hôm nay)
ap = argparse.ArgumentParser(description='Trích các mục QC trong khoảng ngày.')
ap.add_argument('--tu', default='26/09/2026', help='ngày bắt đầu dd/mm/yyyy')
ap.add_argument('--den', default=datetime.date.today().strftime('%d/%m/%Y'), help='ngày kết thúc dd/mm/yyyy')
ap.add_argument('--dich', default=os.path.join(GOC, 'BAOCAOTONGHOP', 'QC_2tuan_0910'), help='thư mục xuất')
args = ap.parse_args()
DICH = args.dich
os.makedirs(DICH, exist_ok=True)


def _tup(s):
    ng, th, nam = (int(x) for x in s.split('/'))
    return (nam, th, ng)


TU, DEN = _tup(args.tu), _tup(args.den)
print('KHOẢNG TRÍCH: %s → %s' % (args.tu, args.den))


def trong_khoang(d):
    m = re.match(r'(\d{2})/(\d{2})/(\d{4})', d or '')
    if not m:
        return False
    ng, th, nam = int(m.group(1)), int(m.group(2)), int(m.group(3))
    return TU <= (nam, th, ng) <= DEN


TU_KHOA = re.compile(r'(ĐẠT|KHÔNG ĐẠT|đạt|không đạt|❌|✅|⚠️|trắng đục|tróc|bám|độ bóng|đốm|rít|mốc|MSSX|'
                     r'\d+[.,]\d+\s*%|\d+\s*%|KPH|kết luận|Kết luận|đề nghị|Đề nghị)')

ra = []
for ten_file, nguoi in TEP:
    s = open(os.path.join(GOC, ten_file), encoding='utf-8', newline='').read()
    phan = re.split(r'(?m)^# ', s)
    for p in phan[1:]:
        dong = p.split('\n')
        tieu_de = dong[0].strip()
        d = re.search(r'CẬP NHẬT\s+(\d{2}/\d{2}/\d{4})', tieu_de) or re.search(r'(\d{2}/\d{2}/\d{4})', tieu_de)
        ngay = d.group(1) if d else ''
        if not trong_khoang(ngay):
            continue
        body = '\n'.join(dong)
        anh = re.findall(r'!\[[^\]]*\]\(([^)]+)\)', body)
        anh = [a for a in anh if not a.startswith('http')]
        heading = re.findall(r'(?m)^(#{2,3})\s*(.+)$', body)
        ket_luan = [l.strip() for l in dong if TU_KHOA.search(l) and not l.strip().startswith('![')]
        ra.append({'nguon': ten_file, 'nguoi': nguoi, 'ngay': ngay, 'tieu_de': tieu_de,
                   'dai': len(body), 'anh': anh,
                   'heading': [(len(h[0]), h[1].strip()[:130]) for h in heading],
                   'ket_luan': [l[:300] for l in ket_luan][:60]})

ra.sort(key=lambda x: (x['ngay'][6:], x['ngay'][3:5], x['ngay'][:2], x['nguoi']))
json.dump(ra, open(os.path.join(DICH, '_trich_xuat_2tuan.json'), 'w', encoding='utf-8'), ensure_ascii=False, indent=1)
print('ĐÃ TRÍCH', len(ra), 'mục →', os.path.join(DICH, '_trich_xuat_2tuan.json'))
print()
for e in ra:
    print('=' * 100)
    print('[%s] %s · %s · %d ký tự · %d ảnh' % (e['nguoi'], e['ngay'], e['tieu_de'][:120], e['dai'], len(e['anh'])))
    print('  HEADING:', ' | '.join(h[1] for h in e['heading'][:8]))
    for l in e['ket_luan'][:14]:
        print('   ·', l)
    if len(e['ket_luan']) > 14:
        print('   · … còn', len(e['ket_luan']) - 14, 'dòng có số liệu')
