# -*- coding: utf-8 -*-
"""NẠP giá dung môi kỳ 06/10/2026 vào CSDL btchem.db (giá theo NCC).
   - backup trước khi ghi
   - loai_gia = 'Giá báo NCC <NCC>' (mỗi NCC 1 loại riêng, UNIQUE (nguyen_lieu_id, ngay, loai_gia))
   - INSERT OR REPLACE ⇒ chạy lại không nhân đôi
   - KHÔNG tự gộp mặt hàng; tên chưa khớp thì BÁO, không tạo bừa
Dùng: python nap_db_dungmoi_0610.py           (dry-run, chỉ in)
      python nap_db_dungmoi_0610.py --commit  (ghi thật)
"""
import datetime, hashlib, importlib.util, os, re, shutil, sqlite3, sys, time, unicodedata

DB = r'C:\c\deepseek-harness\claw2-db\btchem.db'
G = r'C:\Claw 2\Nghien cuu\Tinh-Gia-Thanh\GIA-NGUYEN-LIEU'
PDF = os.path.join(G, 'GIA_DUNG_MOI_06.10.2026.pdf')
NGAY = '2026-10-06'
COMMIT = '--commit' in sys.argv

SK = r'C:\Users\admin\AppData\Local\hermes\skills\productivity\phan-tich-bang-gia\scripts\xu_ly_bang_gia.py'
spec = importlib.util.spec_from_file_location('xlg', SK)
m = importlib.util.module_from_spec(spec); spec.loader.exec_module(m)

# bảng alias đã chốt 22/09/2026 (tên trên báo giá → mặt hàng CHUẨN trong CSDL)
ALIAS = {
    'bcs': 'Ethylene Glycol Butyl Ether (BCS)',
    'dbe': 'Chế phẩm DBE Dibasic ester',
    'd60': 'Exxsol D60',
    'acetone': 'Acetone 160',
    'cellosolve acetate': 'Ethyl Glycol Acetate ( Cellosolve Acetate )',
    'butyl carbitol': 'Diethylene Glycol Monobutyl Ether (Butyl Carbitol)',
    'texanol ester': 'Texanol Ester Alcohol',
}

def nd(s):
    s = unicodedata.normalize('NFD', str(s or '')).encode('ascii', 'ignore').decode()
    return re.sub(r'\s+', ' ', s).strip().lower()

c = sqlite3.connect(DB, timeout=90, isolation_level=None)
c.row_factory = sqlite3.Row
c.execute('PRAGMA busy_timeout=90000')
nl = list(c.execute('select id, ten, nhom from nguyen_lieu'))
by_norm = {}
for r in nl:
    by_norm.setdefault(nd(r['ten']), []).append(r)
print('nguyen_lieu hiện có:', len(nl))

items = m.parse_dungmoi(PDF)
ke_hoach, chua_khop = [], []
for it in items:
    ten = it['ten']
    chuan = ALIAS.get(nd(ten), ten)
    hit = by_norm.get(nd(chuan), [])
    if not hit:
        # tìm gần đúng để cảnh báo (không tự chọn)
        cand = [r['ten'] for r in nl if nd(chuan)[:10] and nd(chuan)[:10] in nd(r['ten'])]
        chua_khop.append((ten, chuan, cand[:4]))
        continue
    nid = hit[0]['id']
    for nc in m.NCC:
        vals = it['cols'].get(nc)
        if not vals:
            continue
        for v in vals:
            g = m.num(v)
            if g:
                ke_hoach.append((nid, hit[0]['ten'], it['ten'], nc, NGAY, 'Giá báo NCC %s' % nc, round(g),
                                 'Báo giá Hằng 06/10/2026 | NCC %s | %s' % (nc, v)))

print('\n=== MẶT HÀNG KHỚP: %d/%d ===' % (len(items) - len(chua_khop), len(items)))
print('=== CHƯA KHỚP (%d) ===' % len(chua_khop))
for t, ch, cand in chua_khop:
    print('   %-32s → chuẩn "%s" | gần đúng: %s' % (t, ch, cand))
print('\n=== DỰ KIẾN GHI: %d dòng giá ===' % len(ke_hoach))
theongay = {}
for k in ke_hoach:
    theongay.setdefault(k[1], []).append(k[3])
for k, v in list(theongay.items())[:35]:
    print('   %-46s %d NCC' % (k, len(v)))

if chua_khop:
    print('\n⚠️ CÒN %d MẶT HÀNG CHƯA KHỚP — cần chủ nhân quyết (không tự tạo/gộp).' % len(chua_khop))

truoc = {t: c.execute('select count(*) from %s' % t).fetchone()[0] for t in ['nguyen_lieu', 'gia_nguyen_lieu', 'file_loaded']}
if not COMMIT:
    print('\n(DRY-RUN) chưa ghi gì. Trước: %s' % truoc)
    sys.exit()

# ---------- BACKUP ----------
bak = DB + '_bak_' + time.strftime('%Y%m%d_%H%M')
s = sqlite3.connect('file:%s?mode=ro' % DB.replace('\\', '/'), uri=True)
d = sqlite3.connect(bak); s.backup(d); d.close(); s.close()
print('backup:', os.path.basename(bak), os.path.getsize(bak), 'byte')

# ---------- GHI ----------
ins = 0
for nid, ten_db, ten_pdf, nc, ngay, loai, gia, gc in ke_hoach:
    c.execute('insert or replace into gia_nguyen_lieu (nguyen_lieu_id, ngay, loai_gia, gia_vnd, ghi_chu) values (?,?,?,?,?)',
              (nid, ngay, loai, gia, gc))
    ins += 1
h = hashlib.sha256(open(PDF, 'rb').read()).hexdigest()
cols = [r[1] for r in c.execute('pragma table_info(file_loaded)')]
row = {'file_path': PDF, 'file_hash': h, 'file_size': os.path.getsize(PDF), 'loai': 'gia',
       'so_dong_nap': ins, 'ngay_nap': datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
       'ket_qua': 'OK - giá dung môi theo NCC kỳ 06/10/2026'}
c.execute('insert into file_loaded (%s) values (%s)' % (','.join(cols), ','.join('?' * len(cols))),
          [row.get(k) for k in cols])
sau = {t: c.execute('select count(*) from %s' % t).fetchone()[0] for t in ['nguyen_lieu', 'gia_nguyen_lieu', 'file_loaded']}
print('đã ghi %d dòng giá' % ins)
print('TRƯỚC → SAU:', truoc, '→', sau)
print('integrity:', c.execute('pragma integrity_check').fetchone()[0])
print()
print('=== KIỂM TRA LẠI 3 MẶT HÀNG ===')
for ma in ['XYLENE', 'MEK', 'TOLUENE']:
    print(' --', ma)
    for r in c.execute("""select n.ten, g.ngay, g.loai_gia, g.gia_vnd from gia_nguyen_lieu g join nguyen_lieu n on n.id=g.nguyen_lieu_id
                          where n.ten like ? and g.ngay=? order by g.loai_gia""", ('%' + ma + '%', NGAY)):
        print('    %-46s %s %-26s %s' % (r['ten'], r['ngay'], r['loai_gia'], '{:,}'.format(r['gia_vnd']).replace(',', '.')))
c.close()
