# -*- coding: utf-8 -*-
r"""B120: bổ sung nha_may.khu_vuc + nha_may.nhom từ các file SX ĐÃ LÀM SẠCH (chỉ điền khi đang TRỐNG).
Backup btchem.db trước; ghi nguồn vào ghi_chu. KHÔNG sửa tên nhà máy, KHÔNG xoá dòng."""
import glob, os, re, shutil, sqlite3, unicodedata
from datetime import datetime
import openpyxl

DB = r'C:\c\deepseek-harness\claw2-db\btchem.db'
KQ = r'C:\Claw 2\Bao cao - Hanh chinh\Bao-cao-sx\LAMSACH\KETQUA'
ds_file = sorted(glob.glob(os.path.join(KQ, 'BANG_BC_SX_TUAN_*_DA-LAM-SACH.xlsx')))
print('  file SX sạch có sẵn: %d' % len(ds_file))
for f in ds_file:
    print('   ', os.path.basename(f))


def chuan(t):
    t = unicodedata.normalize('NFD', (t or '').strip().lower()).replace('đ', 'd')
    t = ''.join(c for c in t if not unicodedata.combining(c))
    return re.sub(r'[^a-z0-9&]', '', t)


# gom khu_vuc / nhom theo tên nhà máy từ MỌI tuần (tuần mới ghi đè tuần cũ)
thong_tin = {}
for f in ds_file:
    wb = openpyxl.load_workbook(f, data_only=True, read_only=True)
    ws = wb[wb.sheetnames[0]]
    for row in ws.iter_rows(min_row=4, values_only=True):
        nm = (row[1] or '').strip() if len(row) > 1 else ''
        if not nm or nm.upper().startswith('KV:') or 'NHÓM' in nm.upper():
            continue
        kv = (row[2] or '').strip() if len(row) > 2 else ''
        qm = (row[4] or '').strip() if len(row) > 4 else ''
        if kv or qm:
            thong_tin[chuan(nm)] = {'kv': kv, 'nhom': qm, 'nguon': os.path.basename(f)[:26]}
    wb.close()
print('  gom được thông tin của %d nhà máy (theo tên chuẩn hoá)' % len(thong_tin))

bk = DB.replace('.db', '_bak_%s.db' % datetime.now().strftime('%Y%m%d_%H%M%S'))
shutil.copy2(DB, bk)
print('  backup:', os.path.basename(bk), os.path.getsize(bk), 'byte')

con = sqlite3.connect(DB, timeout=90, isolation_level=None)
con.execute('PRAGMA busy_timeout=90000')
cur = con.cursor()
truoc_kv = cur.execute("select count(*) from nha_may where coalesce(trim(khu_vuc),'')<>''").fetchone()[0]
truoc_nm = cur.execute("select count(*) from nha_may where coalesce(trim(nhom),'')<>''").fetchone()[0]

con.execute('BEGIN IMMEDIATE')
upd = 0
for i, ten in cur.execute('select id, ten from nha_may').fetchall():
    tt = thong_tin.get(chuan(ten))
    if not tt:
        continue
    kv_hien = cur.execute('select coalesce(khu_vuc,\'\'), coalesce(nhom,\'\'), coalesce(ghi_chu,\'\') from nha_may where id=?', (i,)).fetchone()
    kv_moi = kv_hien[0].strip() or tt['kv']
    nhom_moi = kv_hien[1].strip() or tt['nhom']
    if kv_moi == kv_hien[0].strip() and nhom_moi == kv_hien[1].strip():
        continue
    gc = kv_hien[2]
    vet = '[bổ sung %s từ %s]' % (datetime.now().strftime('%d/%m/%Y'), tt['nguon'])
    if vet not in gc:
        gc = (gc + ' ' + vet).strip()
    cur.execute('update nha_may set khu_vuc=?, nhom=?, ghi_chu=? where id=?', (kv_moi, nhom_moi, gc, i))
    upd += 1
con.execute('COMMIT')

sau_kv = cur.execute("select count(*) from nha_may where coalesce(trim(khu_vuc),'')<>''").fetchone()[0]
sau_nm = cur.execute("select count(*) from nha_may where coalesce(trim(nhom),'')<>''").fetchone()[0]
print('  đã cập nhật %d dòng | khu_vuc có dữ liệu: %d -> %d | nhom: %d -> %d' % (upd, truoc_kv, sau_kv, truoc_nm, sau_nm))
print('  integrity_check:', cur.execute('PRAGMA integrity_check').fetchone()[0])
print('  phân bổ khu vực:', cur.execute("select coalesce(nullif(trim(khu_vuc),''),'(trống)'), count(*) from nha_may group by 1 order by 2 desc").fetchall())
con.close()
