import os
import re

approved_dir = 'docs/design_requests/approved'
drqs = sorted([f for f in os.listdir(approved_dir) if f.startswith('DRQ-20261001-')])

results = []
for f in drqs:
    path = os.path.join(approved_dir, f)
    with open(path, 'r', encoding='utf-8') as fh:
        content = fh.read()
    
    # Check Section 4 deliverables
    sec4_match = re.search(r'## 4\.\s*DANH MỤC TÀI NGUYÊN BÀN GIAO.*?(?=## 5\.|\Z)', content, re.DOTALL | re.IGNORECASE)
    if not sec4_match:
        sec4_match = re.search(r'## 4\..*?(?=## 5\.|\Z)', content, re.DOTALL)
    
    sec4_text = sec4_match.group(0) if sec4_match else ''
    unchecked = re.findall(r'- \[\s*\]', sec4_text)
    checked = re.findall(r'- \[[xX]\]', sec4_text)
    
    # Check Section 5 approvals
    sec5_match = re.search(r'## 5\.\s*BIÊN BẢN NGHIỆM THU.*', content, re.DOTALL | re.IGNORECASE)
    if not sec5_match:
        sec5_match = re.search(r'## 5\..*', content, re.DOTALL)
    
    sec5_text = sec5_match.group(0) if sec5_match else ''
    stage1_pass = ('Stage 1' in sec5_text or 'Cấp 1' in sec5_text) and 'PASS' in sec5_text
    stage2_approved = ('Stage 2' in sec5_text or 'Cấp 2' in sec5_text) and 'APPROVED' in sec5_text
    
    results.append({
        'file': f,
        'checked_count': len(checked),
        'unchecked_count': len(unchecked),
        'stage1_pass': stage1_pass,
        'stage2_approved': stage2_approved
    })

print(f'Total DRQs checked: {len(results)}')
failures = [r for r in results if r['unchecked_count'] > 0 or not r['stage1_pass'] or not r['stage2_approved'] or r['checked_count'] == 0]
if failures:
    print('FAILURES FOUND:')
    for fl in failures:
        print(fl)
else:
    print('ALL 21 DRQs PASSED VERIFICATION!')
    for r in results:
        print(f"{r['file']}: checked={r['checked_count']}, unchecked={r['unchecked_count']}, stage1={r['stage1_pass']}, stage2={r['stage2_approved']}")
