# -*- coding: utf-8 -*-
"""Sửa 3 dòng 'Sai lầm' trong CSDL D (bảng 2 cột bị nạp lệch) + in kiểm chứng toàn bộ."""
import os, re, sqlite3

TMP = os.path.expandvars(r'%LOCALAPPDATA%\Temp\csdlD')
DB = r'C:\Claw 2\Nghien cuu\Du-an-D-Ho-so-vat-lieu\CSDLD.db'
MD = open(os.path.join(TMP, 'cau_hoi_2.md'), encoding='utf-8').read().split('\n')
i = next(k for k, l in enumerate(MD) if 'Sai lầm' in l)
rows = [[re.sub(r'\s+', ' ', x.replace('**', '')).strip().strip('|').strip() for x in l.split('|')]
        for l in MD[i + 1:] if l.count('|') >= 1 and not l.startswith('#')]
con = sqlite3.connect(DB)
c = con.cursor()
c.execute("DELETE FROM luu_y_van_hanh WHERE nhom LIKE 'Sai lầm%'")
for r in rows:
    if r and r[0]:
        c.execute("INSERT INTO luu_y_van_hanh (nhom,noi_dung,ly_do,nguon_id,ngay_cap_nhat) VALUES (?,?,?,1,'2026-10-07')",
                  ('Sai lầm làm vô nghĩa tính toán', r[0], r[1] if len(r) > 1 else ''))
c.execute("INSERT INTO nhat_ky (ngay,viec,chi_tiet,nguon) VALUES ('2026-10-07','Sửa lỗi nạp bảng 2 cột','Bảng Sai lầm nạp lệch cột do bảng chỉ có 2 cột — nạp lại đúng','kiểm chứng nội bộ')")
con.commit()
print('=== CSDL D — KIỂM CHỨNG CUỐI ===')
for (t,) in c.execute("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%' ORDER BY name"):
    print('   %-32s %d dòng' % (t, c.execute('SELECT COUNT(*) FROM ' + t).fetchone()[0]))
print('   integrity:', c.execute('PRAGMA integrity_check').fetchone()[0])
print('\n--- 3 sai lầm (đã sửa) ---')
for r in c.execute("SELECT noi_dung,ly_do FROM luu_y_van_hanh WHERE nhom LIKE 'Sai lầm%'"):
    print('   · %s' % r[0][:95])
    print('     → %s' % r[1][:150])
