# -*- coding: utf-8 -*-
r"""B189b: go CSDL C khoi dashboard — ban sua: xoa bang 'Top khach hang (CSDL C)' theo ANCHOR CHINH XAC,
co in DRY-RUN truoc khi ghi. All-or-nothing."""
import io, os, re, shutil, subprocess, sys, datetime

GOC = r'C:\Claw 2\Nghien cuu\Dashboard-CSDL'
TS = datetime.datetime.now().strftime('%Y%m%d_%H%M')


def nap(f):
    return io.open(os.path.join(GOC, f), encoding='utf-8').read()


def ghi(f, t):
    p = os.path.join(GOC, f)
    io.open(p + '.tmp_ghi', 'w', encoding='utf-8', newline='').write(t)
    os.replace(p + '.tmp_ghi', p)


def xoa_dong(t, chuoi, mong, nhan=''):
    ra, n = [], 0
    for l in t.split('\n'):
        if chuoi in l:
            n += 1
            print('     - XOA [%s] %s' % (nhan, l.strip()[:104]))
        else:
            ra.append(l)
    assert n == mong, 'xoa_dong %r: khop %d (mong %d)' % (chuoi[:50], n, mong)
    return '\n'.join(ra)


def xoa_doan(t, dau, cuoi, nhan=''):
    i = t.find(dau)
    assert i > 0, 'xoa_doan: khong thay dau %r' % dau[:60]
    j = t.find(cuoi, i)
    assert j > 0, 'xoa_doan: khong thay cuoi %r' % cuoi[:60]
    j = t.find('\n', j) + 1
    i = t.rfind('\n', 0, i) + 1
    for l in t[i:j].split('\n'):
        if l.strip():
            print('     - XOA [%s] %s' % (nhan, l.strip()[:104]))
    return t[:i] + t[j:]


def xoa_lenh(t, neo, ten=''):
    """Xoa tron 1 cau lenh Python: neo = dong chua lenh; lui ve dau cau lenh (dong truoc bat dau bang 'hang = [')
    va cat toi het dong chua dong ngoac cua the.append(bang(...))."""
    k = t.find(neo)
    assert k > 0, 'khong thay neo %r' % neo[:60]
    i = t.rfind('hang = [', 0, k)
    assert i > 0, 'khong thay dong bat dau hang = [ truoc neo'
    j = t.find('Top khách hàng theo sản lượng năm 2026 (CSDL C)', k)
    assert j > 0, 'khong thay ket thuc bang CSDL C'
    j = t.find('\n', j) + 1
    print('     - XOA [%s] %d dong:' % (ten, t[i:j].count('\n')))
    for l in t[i:j].split('\n'):
        if l.strip():
            print('       | %s' % l.strip()[:100])
    return t[:i] + t[j:]


# ═══ tab_api.py ═══════════════════════════════════════════════════════════
t = nap('tab_api.py')
shutil.copy2(os.path.join(GOC, 'tab_api.py'), os.path.join(GOC, '_tab_api_truoc_go_CSDLC_%s.bak' % TS))
n0 = len(t)
print('  === DRY-RUN tab_api.py:')
t = xoa_dong(t, "'csdlc': os.environ.get('DASH_DB_CSDLC')", 1, 'DB map')
t = xoa_dong(t, "c = mo('csdlc')", 3, 'dong ket noi')
t = xoa_dong(t, "'Khách hàng (CSDL C)')", 1, 'KPI tong quan')
t = xoa_dong(t, "'Khách nhóm A (CSDL C)')", 1, 'KPI nhom A')
t = xoa_dong(t, "'Bài học kinh nghiệm (CSDL C)')", 1, 'KPI bai hoc')
t = t.replace("'btchem.db · CSDLC.db · CSDLA.db'", "'btchem.db · CSDLA.db'")
t = t.replace("(bảng mua_hang / mua_hang_tong_quan, ghép CSDLC.khach_hang)", "(bảng mua_hang / mua_hang_tong_quan)")
t = t.replace("mua_hang_tong_quan) · CSDLC.db (khach_hang, lich_su_mua_hang)'", "mua_hang_tong_quan)'")
t = t.replace("'btchem.db (su_co_kph) · CSDLC.db (kinh_nghiem)'", "'btchem.db (su_co_kph)'")
assert t.count('b.close(); c.close()') == 2
t = t.replace('b.close(); c.close()', 'b.close()')
t = xoa_doan(t, '# kg theo nhóm / loại khách (ghép CSDLC theo tên chuẩn hoá)',
             "tieu_de='Cơ cấu Kg theo loại khách', kieu='pie'))", 'khoi nhom/loai khach')
t = xoa_lenh(t, 'doc(c, """select ten, tong_kg_2026', 'bang top khach')
t = xoa_doan(t, '# bài học kinh nghiệm (CSDL C) theo tháng',
             "'don_vi': 'bài', 'ngang': False, 'mau': MAU[4]})", 'bieu do bai hoc')
t = xoa_doan(t, 'the.append(cot_ngang(doc(c, """select coalesce(nullif(trim(chu_de)',
             "'bài', 15, 'Chủ đề bài học kinh nghiệm nhiều nhất'))", 'bang chu de bai hoc')
t = t.replace("'Thiếu ngày tạo'),\n", "'Thiếu ngày tạo')]\n")
t = t.replace("'Tổng kg lũy kế'),\n", "'Tổng kg lũy kế')]\n")
assert "c = mo('csdlc')" not in t and 'CSDL C' not in t and 'CSDLC' not in t, 'van con nhac CSDL C'
ghi('tab_api.py', t)
print('  tab_api.py: %d -> %d byte (giam %d)' % (n0, len(t), n0 - len(t)))

# ═══ server_powerbi.py ═══════════════════════════════════════════════════
s = nap('server_powerbi.py')
shutil.copy2(os.path.join(GOC, 'server_powerbi.py'), os.path.join(GOC, '_server_powerbi_truoc_go_CSDLC_%s.bak' % TS))
n1 = len(s)
s = xoa_dong(s, "'csdlc': os.environ.get('DASH_DB_CSDLC')", 1, 'server: DB map')
s = xoa_dong(s, "'csdlc': [('khach_hang', 'count(*)')", 1, 'server: nhip dau')
s = xoa_dong(s, "('lich_su_mua_hang', 'count(*)')]", 1, 'server: nhip cuoi')
s = xoa_dong(s, "cl = sqlite3.connect('file:%s?mode=ro' % DB['csdlc']", 1, 'server: ket noi')
s = xoa_dong(s, "'khach_hang': dem(cl, 'select count(*) from khach_hang')", 1, 'server: KPI khach')
s = xoa_dong(s, "'kinh_nghiem': dem(cl, 'select count(*) from kinh_nghiem')", 1, 'server: KPI bai hoc')
s = re.sub(r"\n[ \t]*cl\.close\(\)", '', s)
assert 'csdlc' not in s.lower() and 'CSDLC' not in s, 'server van con CSDL C'
ghi('server_powerbi.py', s)
print('  server_powerbi.py: %d -> %d byte (giam %d)' % (n1, len(s), n1 - len(s)))

print('\n  === KIEM CHUNG CU PHAP:')
for f in ('tab_api.py', 'server_powerbi.py'):
    r = subprocess.run([sys.executable, '-m', 'py_compile', os.path.join(GOC, f)], capture_output=True, text=True)
    print('     %-20s %s' % (f, 'OK' if r.returncode == 0 else 'LOI: ' + r.stderr.strip()[-300:]))
for f in ('tab_api.py', 'server_powerbi.py'):
    t2 = nap(f)
    con = [l.strip()[:88] for l in t2.split('\n') if re.search(r'csdlc|CSDL C|kinh_nghiem|CSDLC', l, re.I)]
    print('     %-20s con %d dong nhac CSDL C %s' % (f, len(con), con[:2]))
