# -*- coding: utf-8 -*-
"""NẠP thư viện quy trình chuẩn QT_* (Google Drive HETHONGXEMMAU\QUITRINHSON) vào CSDLA.
- backup CSDLA trước khi ghi
- thêm 10 dòng quy_trinh + các dòng buoc_quy_trinh (map sang bộ 34 bước)
- thêm 1 dòng nguon_quet
- chỉ THÊM, không sửa/xoá dòng cũ
"""
import glob, io, os, re, shutil, sqlite3, time

D = r'C:\Claw 2\Nghien cuu\Du-an-A-Quy-trinh-son'
ND = os.path.join(D, 'nguon_HETHONGXEMMAU')
DB = os.path.join(D, 'CSDLA.db')

# ---------- 1. backup ----------
ts = time.strftime('%Y%m%d_%H%M%S')
bak = os.path.join(D, '_backup_CSDLA_truoc_nguon_HETHONGXEMMAU_%s.db' % ts)
shutil.copy2(DB, bak)
print('backup:', os.path.basename(bak), os.path.getsize(bak), 'byte')

c = sqlite3.connect(DB)
truoc = {t: c.execute('select count(*) from %s' % t).fetchone()[0]
         for t in ['buoc_chuan', 'quy_trinh', 'buoc_quy_trinh', 'phong_cach', 'cong_thuc', 'danh_muc_mau', 'nguon_quet']}
print('trước:', truoc)
old_ids = set(r[0] for r in c.execute('select id from quy_trinh'))

# ---------- 2. map bước chuẩn ----------
def map_buoc(ten, vt, lan_lot):
    s = (ten + ' ' + vt).lower()
    if re.search(r'chuẩn bị bề mặt|xả phẳng|nhám mộc|chà nhám mộc|đánh nhám', s):
        return 16
    if 'ngăn dầu' in s or 'chặn nhựa' in s or 'chặn tannin' in s or 'chống thấm' in s:
        return 25
    if 'bột bụi' in s or 'bột lau' in s:
        return 11
    if 'glaze' in s:
        return 9
    if 'đánh cọ' in s:
        return 12
    if 'chà nhám' in s or 'xả nhám' in s or 'hút sạch bụi nhám' in s:
        return 33
    if 'nhuộm' in s or 'stain' in s or 'lau màu' in s or 'dặm màu' in s:
        return 5
    if 'lót màu' in s:
        return 8
    if 'lót' in s:
        return 19 if lan_lot == 0 else 20
    if 'bệt' in s or 'sơn màu' in s or 'màu đặc' in s:
        return 8
    if 'dầu' in s or 'obt' in s:
        return 24
    if 'phủ' in s or 'bóng' in s or 'topcoat' in s or 'mờ' in s:
        return 21
    if 'vá' in s or 'trám' in s or 'bột trét' in s:
        return 28
    if 'trét lấp' in s or 'lấp ghim' in s:
        return 29
    return None

def lay_gt(t, nhan):
    m = re.search(r'\*\*%s:\*\*\s*(.+?)\s*$' % nhan, t, re.M)
    return m.group(1).strip() if m else None

files = sorted(glob.glob(os.path.join(ND, 'QT_*.md')))
print('\n=== nạp %d quy trình chuẩn ===' % len(files))
tong_buoc = 0
chua_map = 0
for f in files:
    t = io.open(f, encoding='utf-8').read()
    ten = os.path.splitext(os.path.basename(f))[0]
    he = lay_gt(t, 'Hệ sơn') or ''
    mau = lay_gt(t, 'Màu sắc')
    vitri = lay_gt(t, 'Vị trí áp dụng')
    cot = lay_gt(t, 'Cốt gỗ áp dụng')
    bong = lay_gt(t, 'Độ bóng')
    he_son = (re.search(r'\b(NC|PU|AC|OBT)\b', he) or [None, he[:20]])[1]
    # các dòng bảng bước
    hang = [l for l in t.split('\n') if l.startswith('|') and not re.match(r'^\|[\s:|-]+\|$', l) and 'STT' not in l]
    buoc = []
    lan_lot = 0
    for l in hang:
        o = [x.strip() for x in l.strip('|').split('|')]
        if len(o) < 2:
            continue
        stt, quy, hoa = o[0], o[1], (o[2] if len(o) > 2 else '')
        ti, tb, kho = (o[3] if len(o) > 3 else ''), (o[4] if len(o) > 4 else ''), (o[5] if len(o) > 5 else '')
        dinh = o[6] if len(o) > 6 else ''
        quy_s = re.sub(r'\*\*|~|`', '', quy).replace('<br>', ' ')
        hoa_s = re.sub(r'\*\*|~|`', '', hoa).replace('<br>', ' + ')
        nb = map_buoc(quy_s, hoa_s, lan_lot)
        if nb == 20 or (nb == 19 and lan_lot > 0):
            lan_lot += 1
        if 'lót' in quy_s.lower():
            lan_lot += 1
        nt = 'Bước %s: %s — %s' % (stt, quy_s, hoa_s)
        gc = ' | '.join(x for x in ['tỉ lệ: ' + re.sub(r'\*\*|`', '', ti) if ti and ti != '—' else '',
                                    'thi công: ' + re.sub(r'\*\*|`', '', tb) if tb else '',
                                    'khô: ' + re.sub(r'\*\*|`', '', kho) if kho and kho != '—' else '',
                                    'định lượng: ' + dinh + ' kg/m²' if dinh and dinh != '—' else ''] if x)
        buoc.append((nt, nb, gc))
        if nb is None:
            chua_map += 1
    c.execute("""insert into quy_trinh (ten, loai, khach_hang, nha_may_id, he_son, ma_mau, so_buoc, mo_ta, nguon, ngay_tai_lieu, ghi_chu)
                 values (?,?,?,?,?,?,?,?,?,?,?)""",
              (ten, 'Quy trình chuẩn công ty (HETHONGXEMMAU/QUITRINHSON)', None, None, he_son, mau, len(buoc),
               'Vị trí: %s | Cốt gỗ: %s | Độ bóng: %s' % (vitri, cot, bong), f, '2026-07-17',
               'Thư viện quy trình chuẩn nội bộ (Google Drive HETHONGXEMMAU\\QUITRINHSON); nạp vào CSDLA ngày 06/10/2026'))
    qid = c.execute('select last_insert_rowid()').fetchone()[0]
    for i, (nt, nb, gc) in enumerate(buoc, 1):
        c.execute("""insert into buoc_quy_trinh (quy_trinh_id, thu_tu, buoc_nguyen_van, buoc_chuan_so, ghi_chu)
                     values (?,?,?,?,?)""", (qid, i, nt, nb, gc))
    tong_buoc += len(buoc)
    da_map = sum(1 for _, nb, _ in buoc if nb)
    print('   [%2d] %-52s %-4s %2d bước (%d đã map)  | %s' % (qid, ten, he_son, len(buoc), da_map, mau[:52]))

c.execute("""insert into nguon_quet (nguon, loai, so_ban_ghi, ngay_quet, ghi_chu) values (?,?,?,?,?)""",
          ('Google Drive HETHONGXEMMAU\\QUITRINHSON — thư viện quy trình chuẩn QT_*',
           'Thư viện quy trình chuẩn nội bộ (tài liệu công ty)', len(files), time.strftime('%Y-%m-%d'),
           'Tải qua Drive API; lưu bản gốc tại Du-an-A-Quy-trinh-son\\nguon_HETHONGXEMMAU\\; gồm 10 quy trình QT_ (PG/ST, IN/OUT, hệ NC/PU/AC/OBT)'))
c.commit()

sau = {t: c.execute('select count(*) from %s' % t).fetchone()[0]
       for t in ['buoc_chuan', 'quy_trinh', 'buoc_quy_trinh', 'phong_cach', 'cong_thuc', 'danh_muc_mau', 'nguon_quet']}
print('\nsau :', sau)
print('tăng: quy_trinh +%d | buoc_quy_trinh +%d | nguon_quet +%d | tổng bước nạp %d (chưa map %d)'
      % (sau['quy_trinh'] - truoc['quy_trinh'], sau['buoc_quy_trinh'] - truoc['buoc_quy_trinh'],
         sau['nguon_quet'] - truoc['nguon_quet'], tong_buoc, chua_map))
m = c.execute('pragma integrity_check').fetchone()[0]
print('integrity:', m)
print('dòng cũ còn nguyên:', all(c.execute('select count(*) from quy_trinh where id=?', (i,)).fetchone()[0] == 1 for i in list(old_ids)[:20]))
print('mtime:', time.strftime('%H:%M:%S', time.localtime(os.path.getmtime(DB))), '| size', os.path.getsize(DB))
c.close()
