# -*- coding: utf-8 -*-
r"""B80: đếm mã placeholder 'Chưa có tên' trong file sạch T41 + mã mới (nha_may/KTV loader tự tạo)."""
import collections, sqlite3
import openpyxl

SACH = r'C:\Claw 2\Bao cao - Hanh chinh\Bao cao lam mau\da lam sach\Tuan_41_05.10-11.10_DA-LAM-SACH.xlsx'
c = sqlite3.connect('file:C:/c/deepseek-harness/claw2-db/btchem.db?mode=ro', uri=True)

wb = openpyxl.load_workbook(SACH, read_only=True, data_only=True)
ws = wb[wb.sheetnames[0]]
rows = [r for r in ws.iter_rows(values_only=True) if any(x not in (None, '') for x in r)]
hdr = [str(x or '').strip() for x in rows[0]]
I = {h: i for i, h in enumerate(hdr)}
ph = collections.Counter()
for r in rows[1:]:
    ma = str(r[I['Mã NM']] or '').strip() or str(r[I['Mã PT/KH']] or '').strip()
    if ma and not any(ch.isdigit() for ch in ma):
        ph[ma] += 1
wb.close()
print('  mã KHÔNG có chữ số (nghi placeholder) trong file:', dict(ph.most_common(6)))

print()
print('  === nhà máy / KTV MỚI do loader tự tạo (so với backup) ===')
BAK = r'C:\c\deepseek-harness\claw2-db\btchem.db_bak_20261012_190627_truoc_nap_mau_lam_T41'
b = sqlite3.connect('file:%s?mode=ro' % BAK.replace('\\', '/'), uri=True)
old_nm = {r[0] for r in b.execute('select ten from nha_may')}
old_kt = {r[0] for r in b.execute('select ten from phai_vien_kt')}
b.close()
new_nm = [r[0] for r in c.execute('select ten from nha_may') if r[0] not in old_nm]
new_kt = [r[0] for r in c.execute('select ten from phai_vien_kt') if r[0] not in old_kt]
print('  nhà máy mới: %s' % new_nm)
print('  KTV mới   : %s' % new_kt)
print()
print('  T41 tóm tắt:', c.execute("select count(*), count(distinct nha_may_id) from mau_lam where tuan='T41'").fetchone(), '| tổng bảng mau_lam:', c.execute('select count(*) from mau_lam').fetchone()[0])
c.close()
