# -*- coding: utf-8 -*-
r"""B51: soi bảng đích su_co_kph + nha_may trong btchem.db (để ghi sự cố theo nhà máy)."""
import os, sqlite3, shutil, datetime

B = r'C:\c\deepseek-harness\claw2-db\btchem.db'
tem = datetime.datetime.now().strftime('%Y%m%d_%H%M')
BAK = B.replace('btchem.db', 'btchem.db_bak_%s_truoc_ghi_su_co_kph_QC' % tem)
shutil.copy2(B, BAK)
print('  BACKUP:', BAK, os.path.getsize(BAK), 'B')

c = sqlite3.connect('file:%s?mode=ro' % B.replace('\\', '/'), uri=True)
print()
print('  DDL su_co_kph:', c.execute("select sql from sqlite_master where name='su_co_kph'").fetchone()[0])
print()
print('  su_co_kph:', c.execute('select count(*) from su_co_kph').fetchone()[0], 'dòng')
print('  5 dòng mẫu (định dạng thật):')
for r in c.execute('''select id, id_vu_viec, ngay_tao, nguoi_tao, giao_cho, ten_vu_viec, nha_may_id, san_pham_mau, loai_sai,
                             giai_doan, trang_thai, ngay_kt, nguyen_nhan, ket_qua, phuong_an_xu_ly, ngay_hoan_thanh, nguoi_theo_doi, nguon
                      from su_co_kph order by id desc limit 5'''):
    for k, v in zip(('id', 'id_vu_viec', 'ngay_tao', 'nguoi_tao', 'giao_cho', 'ten_vu_viec', 'nha_may_id', 'san_pham_mau',
                     'loai_sai', 'giai_doan', 'trang_thai', 'ngay_kt', 'nguyen_nhan', 'ket_qua', 'phuong_an_xu_ly',
                     'ngay_hoan_thanh', 'nguoi_theo_doi', 'nguon'), r):
        if v not in (None, ''):
            print('      %-16s %s' % (k, str(v)[:150]))
    print('      ---')
print()
print('  nha_may (%d dòng) — id | ten | nhom/khu vực:' % c.execute('select count(*) from nha_may').fetchone()[0])
for r in c.execute('select id, ten, ifnull(khu_vuc,""), ifnull(nhom,"") from nha_may order by id'):
    print('   %-4s %-44s %-14s %s' % (r[0], str(r[1])[:44], str(r[2])[:14], str(r[3])[:22]))
c.close()
