# -*- coding: utf-8 -*-
r"""B72: KIỂM CHỨNG ĐỘC LẬP tuần 41 — tự tính lại từ file, đối chiếu báo cáo agy."""
import collections, os
import openpyxl

SACH = r'C:\Claw 2\Bao cao - Hanh chinh\Bao cao lam mau\da lam sach'
FILES = [('GỘP', 'Tuan_41_05.10-11.10_DA-LAM-SACH.xlsx'),
         ('File1_Chinh', 'Tuan_41_File1_Chinh_DA-LAM-SACH.xlsx'),
         ('File2_KQM', 'Tuan_41_File2_KQM_DA-LAM-SACH.xlsx'),
         ('File3_W41', 'Tuan_41_File3_W41_DA-LAM-SACH.xlsx')]


def doc(p):
    wb = openpyxl.load_workbook(p, read_only=True, data_only=True)
    ws = wb[wb.sheetnames[0]]
    rows = [r for r in ws.iter_rows(values_only=True) if any(c not in (None, '') for c in r)]
    wb.close()
    return rows


def tk(rows, ten):
    hdr = [str(c or '').strip() for c in rows[0]]
    idx = {h: i for i, h in enumerate(hdr)}
    def g(r, col):
        i = idx.get(col)
        return r[i] if (i is not None and i < len(r) and r[i] is not None) else ''
    nm_raw, nm_ff = set(), set()
    cur = ''
    sl, co_ma, co_dh, co_kt = 0, 0, 0, 0
    loai, tt = collections.Counter(), collections.Counter()
    for r in rows[1:]:
        nm = str(g(r, 'Nhà máy')).strip()
        if nm:
            nm_raw.add(nm)
            cur = nm
        elif cur:
            nm_ff.add(cur)
        nm_ff.add(cur) if cur else None
        if nm:
            nm_ff.add(nm)
        if str(g(r, 'Mã NM')).strip() or str(g(r, 'Mã PT/KH')).strip():
            co_ma += 1
        if str(g(r, 'Có ĐH')).strip():
            co_dh += 1
        if str(g(r, 'Kỹ thuật')).strip():
            co_kt += 1
        v = str(g(r, 'Số lượng')).strip().replace('.', '').replace(',', '')
        if v.isdigit():
            sl += int(v)
        loai[str(g(r, 'Loại mẫu')).strip() or '(trống)'] += 1
        tt[str(g(r, 'Trạng thái')).strip() or '(trống)'] += 1
    return dict(ten=ten, dong=len(rows) - 1, nm_raw=len(nm_raw), nm_ff=len(nm_ff),
                sl=sl, co_ma=co_ma, co_dh=co_dh, co_kt=co_kt, loai=loai, tt=tt)


kq = {}
for ten, f in FILES:
    p = os.path.join(SACH, f)
    kq[ten] = tk(doc(p), ten)
    k = kq[ten]
    print('  %-12s dòng=%-4d | nhà máy (raw/điền-tiếp)=%d/%d | SL=%-6d | có mã=%-4d | có ĐH=%-3d | có KTV=%-4d'
          % (ten, k['dong'], k['nm_raw'], k['nm_ff'], k['sl'], k['co_ma'], k['co_dh'], k['co_kt']))

print()
print('  === PHÉP KIỂM MẠNH NHẤT: 3 file thành phần vs FILE GỘP ===')
d = sum(kq[t]['dong'] for t in ('File1_Chinh', 'File2_KQM', 'File3_W41'))
s = sum(kq[t]['sl'] for t in ('File1_Chinh', 'File2_KQM', 'File3_W41'))
print('   dòng:  %d + %d + %d = %d  |  file gộp = %d  →  %s' % (
    kq['File1_Chinh']['dong'], kq['File2_KQM']['dong'], kq['File3_W41']['dong'], d, kq['GỘP']['dong'],
    'KHỚP ✓' if d == kq['GỘP']['dong'] else 'LỆCH ✗'))
print('   sản lượng: %d  |  file gộp = %d  →  %s' % (s, kq['GỘP']['sl'], 'KHỚP ✓' if s == kq['GỘP']['sl'] else 'LỆCH ✗'))

print()
print('  === ĐỐI CHIẾU VỚI BÁO CÁO AGY ===')
g = kq['GỘP']
print('   nhà máy riêng biệt: agy ghi 48 | em đếm = %d (raw) / %d (điền tiếp) → %s' % (
    g['nm_raw'], g['nm_ff'], 'KHỚP ✓' if g['nm_ff'] == 48 or g['nm_raw'] == 48 else 'LỆCH → báo đúng số, không sửa file'))
print('   tổng dòng: agy 183 | em đếm %d → %s' % (g['dong'], 'KHỚP ✓' if g['dong'] == 183 else 'LỆCH ✗'))
print('   sản lượng: agy 1394 | em tính %d → %s' % (g['sl'], 'KHỚP ✓' if g['sl'] == 1394 else 'LỆCH ✗'))
print('   có đơn hàng: agy 8 | em đếm %d → %s' % (g['co_dh'], 'KHỚP ✓' if g['co_dh'] == 8 else 'LỆCH ✗'))
print('   loại mẫu (agy: Mới 71 · Nhân 33 · Bộ 68 · không làm/chưa rõ 11):')
for k, v in g['loai'].most_common():
    print('      %-28s %d' % (k, v))
print('   trạng thái (agy: DK 23 · HT 139 · ĐL 21):')
for k, v in g['tt'].most_common():
    print('      %-28s %d' % (k, v))
print('   số dòng CÓ MÃ mẫu (Mã NM/Mã PT-KH): %d  ← dùng cho portal + CSDL' % g['co_ma'])
print('   số KTV khác nhau (chuỗi thô):', len({str(r) for r in []}) or 'xem dưới')
