# -*- coding: utf-8 -*-
r"""B82b: (1) mẫu CHƯA dứt điểm T38-T41; (2) mã xuất hiện nhiều tuần chưa ký/hoàn thành; (3) thiếu KTV; (4) nhà máy có mẫu mà không thấy trong báo cáo KT tuần."""
import collections, sqlite3

DB = r'C:\c\deepseek-harness\claw2-db\btchem.db'
c = sqlite3.connect('file:%s?mode=ro' % DB.replace('\\', '/'), uri=True)
c.row_factory = sqlite3.Row

print('=== 1. MẪU CHƯA DỨT ĐIỂM (Đang làm / ĐL) T38 → T41 ===')
rows = c.execute("""select m.tuan as tuan, ifnull(n.ten,'(chua ro)') as nm, m.ma_mau as ma, ifnull(m.khach_hang,'') as kh,
                           m.ngay_nhan as nn, ifnull(m.ngay_ht,'') as ht, ifnull(k.ten,'(thiếu KTV)') as ktv, ifnull(m.ghi_chu,'') as gh
                    from mau_lam m left join nha_may n on n.id=m.nha_may_id left join phai_vien_kt k on k.id=m.ky_thuat_id
                    where m.tuan in ('T38','T39','T40','T41') and ifnull(m.trang_thai,'') in ('Đang làm','ĐL')
                    order by m.tuan, nm""").fetchall()
print('   tổng %d dòng | theo tuần: %s' % (len(rows), dict(collections.Counter(r['tuan'] for r in rows))))
for r in rows:
    print('   %-4s %-18s %-16s %-13s nhận %-11s HT %-11s | %-16s | %s' % (
        r['tuan'], str(r['nm'])[:18], str(r['ma'])[:16], str(r['kh'])[:13], str(r['nn'])[:11], str(r['ht'])[:11],
        str(r['ktv'])[:16], str(r['gh'])[:40]))

print()
print('=== 2. MÃ XUẤT HIỆN ≥2 TUẦN TRONG T38–T41 MÀ CHƯA TỪNG KÝ/HOÀN THÀNH ===')
d = collections.defaultdict(list)
for r in c.execute("""select m.tuan as tuan, ifnull(n.ten,'(chua ro)') as nm, m.ma_mau as ma, ifnull(m.trang_thai,'') as tt,
                             ifnull(m.khach_hang,'') as kh, m.ngay_nhan as nn
                      from mau_lam m left join nha_may n on n.id=m.nha_may_id
                      where m.tuan in ('T38','T39','T40','T41') and ifnull(m.ma_mau,'')<>'' """):
    d[(r['nm'], r['ma'])].append((r['tuan'], r['tt'], r['kh'], r['nn']))
nhieu = {k: v for k, v in d.items() if len({x[0] for x in v}) >= 2}
chua = {k: v for k, v in nhieu.items() if not any(x[1] in ('Đã ký', 'Đã hoàn thành', 'HT', 'DK') for x in v)}
print('   mã xuất hiện ≥2 tuần: %d | chưa từng ký/hoàn thành: %d' % (len(nhieu), len(chua)))
for (nm, ma), v in list(chua.items())[:20]:
    print('   %-20s %-16s → %s | KH %s' % (str(nm)[:20], str(ma)[:16], ['%s:%s' % (x[0], x[1]) for x in v], str(v[-1][2])[:16]))
print('   --- và các mã ≥2 tuần ĐÃ có ký/hoàn thành (để loại trừ):', len(nhieu) - len(chua))

print()
print('=== 3. MẪU THIẾU KTV theo tuần ===')
for r in c.execute("""select tuan as t, count(*) as tong, sum(case when ifnull(ky_thuat_id,'')='' then 1 else 0 end) as thieu
                      from mau_lam where tuan in ('T38','T39','T40','T41') group by tuan order by tuan"""):
    print('   %-4s tổng %3d | thiếu KTV %3d' % (r['t'], r['tong'], r['thieu']))

print()
print('=== 4. NHÀ MÁY CÓ MẪU NHƯNG KHÔNG THẤY TÊN TRONG BÁO CÁO KT TUẦN ===')
for t in ('T39', 'T40', 'T41'):
    bc = ' '.join((r[0] or '') for r in c.execute('select noi_dung from bao_cao_kt_tuan where tuan=?', (t,)))
    nm_co_mau = [r[0] for r in c.execute("""select distinct n.ten as ten from mau_lam m join nha_may n on n.id=m.nha_may_id
                                            where m.tuan=? and n.ten is not null""", (t,))]
    thieu = [nm for nm in nm_co_mau if nm and nm.upper() not in bc.upper()]
    print('   %s: %2d nhà máy có mẫu | KHÔNG thấy trong báo cáo KT tuần: %2d → %s' % (t, len(nm_co_mau), len(thieu), [str(x)[:16] for x in thieu[:14]]))
c.close()
