# -*- coding: utf-8 -*-
r"""B188: kiem chung portal sau khi chen + bo sung 5 khoi moi vao portal_map.blocks."""
import io, json, os, re
from bs4 import BeautifulSoup

GOC = r'C:\Claw 2\Bao cao - Hanh chinh\BAOCAOTONGHOP\HTML\KPH_TongHop_0508'
PORTAL = os.path.join(GOC, 'index.html')
MAP = r'C:\claw\Khieu Nai KHach Hang\portal_map.json'
h = io.open(PORTAL, encoding='utf-8').read()
print('  === KIEM CHUNG CAU TRUC')
print('     file %d byte | LF %d | CRLF %d' % (len(h.encode()), h.count('\n'), h.count('\r\n')))
print('     khoi class="inc": %d | <div>: %d | </div>: %d %s' % (
    h.count('class="inc"'), h.count('<div'), h.count('</div>'),
    'CÂN BẰNG' if h.count('<div') == h.count('</div>') else 'LỆCH!'))
print('     <figure>: %d | </figure>: %d %s' % (h.count('<figure'), h.count('</figure>'),
      'CÂN BẰNG' if h.count('<figure') == h.count('</figure>') else 'LỆCH!'))
print('     so vu ghi trong file:', re.findall(r'(\d+)\s*vụ việc', h)[:4], '|', re.findall(r'(\d+)\s*vụ —', h)[:2])

soup = BeautifulSoup(h, 'html.parser')
inc = soup.select('div.inc')
print('     BeautifulSoup: %d khoi | so khoi co id: %d' % (len(inc), sum(1 for x in inc if x.get('id'))))
ids = [x.get('id') for x in inc if x.get('id')]
print('     id trung lap:', [i for i in set(ids) if ids.count(i) > 1] or 'khong co')

MOI = [('tanviettien-tvtwhite', 43, 'Tân Việt Tiến — Màu TVT White'),
       ('hanhphuc-hp269', 44, 'Hạnh Phúc — Màu HP 269'),
       ('hanhmy-bex032402', 45, 'Hành Mỹ — Bóng Bex 03-2402 H 25%'),
       ('mekong3-mk1217h', 46, 'Mekong 3 — Màu MK 12/17 H'),
       ('minhhungtien-mht02', 47, 'Minh Hưng Tiến — Màu MHT 02')]
print('\n  === 5 KHOI MOI:')
for slug, no, ten in MOI:
    blk = [x for x in inc if x.get('id') == slug]
    if not blk:
        print('     %-22s KHONG THAY!' % slug); continue
    blk = blk[0]
    body = blk.find('div', class_='inc-body')
    print('     %-22s no=%s | trong inc-body: %d ky tu | con truc tiep: %s' % (
        slug, (blk.find('span', class_='no') or {}).get_text(strip=True) if blk.find('span', class_='no') else '?',
        len(body.get_text(' ', strip=True)) if body else 0,
        [c.name + '.' + '.'.join(c.get('class', [])) for c in blk.find_all(recursive=False)]))

print('\n  === 5 PANEL BO SUNG (phai nam TRONG khoi dich):')
for slug in ('tienhung-tth270', 'thanhthang-thth91', 'danglong-dlo11', 'mekong3', 'tv'):
    blk = [x for x in inc if x.get('id') == slug]
    if not blk:
        print('     %-20s KHONG THAY' % slug); continue
    body = blk[0].find('div', class_='inc-body')
    txt = body.get_text(' ', strip=True) if body else blk[0].get_text(' ', strip=True)
    ok = 'Bổ sung 14/10/2026' in txt
    so_panel = len(blk[0].find_all('div', class_='sub'))
    print('     %-20s panel trong inc-body: %-5s | so div.sub: %d' % (slug, ok, so_panel))

print('\n  === ANH: kiem file ton tai')
thieu = []
for m in re.finditer(r'<img[^>]+src="([^"]+)"', h):
    src = m.group(1)
    if src.startswith('data:') or not src:
        continue
    p = os.path.join(GOC, src.replace('/', os.sep))
    if not os.path.exists(p):
        thieu.append(src)
print('     anh tham chieu: %d | thieu file: %d %s' % (len(re.findall(r'<img[^>]+src="[^"]+"', h)), len(thieu), thieu[:5]))

# ── bo sung portal_map.blocks ────────────────────────────────────────────
m = json.load(io.open(MAP, encoding='utf-8'))
blocks = m.get('blocks', {})
print('\n  === portal_map: blocks %d -> ' % len(blocks), end='')
for slug, no, ten in MOI:
    blk = [x for x in inc if x.get('id') == slug]
    if not blk:
        continue
    t = re.sub(r'\s+', ' ', blk[0].get_text(' ', strip=True))
    t = re.sub(r'^\d+\s*', '', t)          # bỏ số thứ tự đầu text khối (bẫy lặp số của skill)
    blocks[slug] = str(no) + ' ' + t[:118]
    assert not blocks[slug][:12].split(' ')[0:2][1].isdigit() or True
bs = m.setdefault('by_hoso', {})
bs.update({'829': 'tanviettien-tvtwhite', '830': 'hanhphuc-hp269', '831': 'hanhmy-bex032402'})
m['blocks'] = blocks
io.open(MAP + '.tmp_ghi', 'w', encoding='utf-8').write(json.dumps(m, ensure_ascii=False, indent=1))
os.replace(MAP + '.tmp_ghi', MAP)
print('%d' % len(blocks))
print('     by_hoso: %d muc (co 829/830/831: %s)' % (len(bs), all(x in bs for x in ('829', '830', '831'))))
for slug, no, ten in MOI:
    if slug in blocks:
        print('     %-22s -> %s' % (slug, blocks[slug][:80]))
