# -*- coding: utf-8 -*-
r"""B137: thử tab_api cho cả 6 tab — in số KPI đầu, số thẻ, vài con số để đối chiếu SQL."""
import importlib.util, sys, time

spec = importlib.util.spec_from_file_location('ta', r'C:\Claw 2\Nghien cuu\Dashboard-CSDL\tab_api.py')
ta = importlib.util.module_from_spec(spec)
spec.loader.exec_module(ta)

for tab, (ten, ham) in ta.TABS.items():
    t0 = time.time()
    try:
        d = ta.api({'tab': tab})
        ms = int((time.time() - t0) * 1000)
        loai = {}
        for x in d['the']:
            loai[x['loai']] = loai.get(x['loai'], 0) + 1
        print('OK   %-9s %-18s %4d ms | KPI %d | thẻ %d %s' % (tab, ten, ms, len(d['kpi']), len(d['the']), loai))
        for k in d['kpi'][:4]:
            print('        · %-12s %s' % (k['n'], k['t']))
    except Exception as e:
        print('LỖI  %-9s %s: %s' % (tab, type(e).__name__, e))

# đối chiếu vài con số với SQL trực tiếp
import sqlite3
b = sqlite3.connect('file:C:/c/deepseek-harness/claw2-db/btchem.db?mode=ro', uri=True)
print('\nĐỐI CHIẾU SQL:')
print('  kg T10      :', b.execute("select sum(tong_kg) from mua_hang where ky='T10'").fetchone()[0])
print('  sự cố       :', b.execute('select count(*) from su_co_kph').fetchone()[0],
      '| chưa xong:', b.execute("select count(*) from su_co_kph where lower(coalesce(trang_thai,'')) not like '%đã xử lý%'").fetchone()[0])
print('  mẫu T41     :', b.execute("select count(*) from mau_lam where tuan='T41'").fetchone()[0],
      '| đang làm:', b.execute("select count(*) from mau_lam where upper(coalesce(trang_thai,'')) in ('ĐL','ĐANG LÀM')").fetchone()[0])
print('  cont T41    :', b.execute("select round(sum(so_cont),1) from bao_cao_sx where tuan='T41'").fetchone()[0])
print('  báo cáo KT  :', b.execute('select count(*) from bao_cao_kt_tuan').fetchone()[0])
a = sqlite3.connect('file:C:/Claw 2/Nghien cuu/Du-an-A-Quy-trinh-son/CSDLA.db?mode=ro', uri=True)
print('  CSDL A      :', a.execute('select count(*) from quy_trinh').fetchone()[0], 'quy trình /',
      a.execute('select count(*) from buoc_quy_trinh').fetchone()[0], 'bước')
