# -*- coding: utf-8 -*-
r"""B36: bóc các MỤC trong khoảng 28/09/2026 -> 10/10/2026 từ Locqc.md + 'Tri qc.md' -> file làm việc."""
import os, re

QC = r'C:\Claw 2\QC'
DICH = os.path.join(QC, '_tomtat_2809_1010')
os.makedirs(DICH, exist_ok=True)
TU, DEN = (28, 9), (10, 10)  # ngày/tháng 2026


def trong_khoang(d, m):
    return (m == 9 and d >= 28) or (m == 10 and d <= 10)


for nguon, ten in (('Locqc.md', 'LOC'), ('Tri qc.md', 'TRI')):
    s = open(os.path.join(QC, nguon), encoding='utf-8', errors='replace').read()
    # tách theo heading mục
    phan = re.split(r'(?m)^(?=# BÁO CÁO)', s)
    chon = []
    for p in phan:
        m = re.match(r'# BÁO CÁO[^\n]*?CẬP NHẬT\s+(\d{1,2})/(\d{1,2})/(\d{4})', p)
        if not m:
            continue
        d, th, y = int(m.group(1)), int(m.group(2)), int(m.group(3))
        if y == 2026 and trong_khoang(d, th):
            chon.append((d, th, p.strip()))
    chon.sort(key=lambda x: (x[1], x[0]))
    out = os.path.join(DICH, 'NGUON_%s.md' % ten)
    open(out, 'w', encoding='utf-8', newline='').write('\n\n'.join(x[2] for x in chon))
    print('  %-10s %d mục trong khoảng | file %s (%d B)' % (ten, len(chon), os.path.basename(out), os.path.getsize(out)))
    for d, th, p in chon:
        print('     %02d/%02d  %5d ký tự | %s' % (d, th, len(p), p.split('\n', 1)[0][:120]))
print()
print('  thư mục làm việc:', DICH)
