# -*- coding: utf-8 -*-
r"""B79: xác định 6 dòng file có mã nhưng không vào DB (UNIQUE nuốt) — dùng ĐÚNG tên cột."""
import collections, sqlite3
import openpyxl

DB = r'C:\c\deepseek-harness\claw2-db\btchem.db'
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:%s?mode=ro' % DB.replace('\\', '/'), uri=True)
cols = [r[1] for r in c.execute('pragma table_info(mau_lam)')]
print('  cột mau_lam:', ', '.join(cols))
print('  UNIQUE:', [r[0] for r in c.execute("select sql from sqlite_master where name like '%mau_lam%'")][:1])

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)}
wb.close()

khoa = 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 not ma:
        continue
    ngay = str(r[I['Ngày nhận']] or '').strip()
    khoa[(ma, ngay)] += 1
trung = {k: v for k, v in khoa.items() if v > 1}
print()
print('  file: %d dòng có mã | số cặp (mã, ngày nhận) TRÙNG trong file: %d (tổng dòng dư: %d)'
      % (sum(khoa.values()), len(trung), sum(v - 1 for v in trung.values())))
for (ma, ngay), v in list(trung.items())[:10]:
    print('     - %-18s %-12s × %d' % (ma[:18], ngay[:12], v))
print()
print('  DB T41 = 166 dòng | file 172 dòng có mã | chênh %d dòng (bị UNIQUE nuốt, nội dung được nối vào ghi_chu)'
      % (172 - 166))
print('  kiểm ghi_chu có nối loại mẫu khác:', c.execute(
    "select count(*) from mau_lam where tuan='T41' and ifnull(ghi_chu,'') like '%[%' ").fetchone()[0], 'dòng')
c.close()
