# -*- coding: utf-8 -*-
r"""B147: TÁCH đối thủ + số liệu từ cột canh_tranh (văn bản tự do) — kiểm tra trước khi đưa lên dashboard.
Lưu ý: 'Bình Thạnh' là SƠN CỦA MÌNH (không tính là đối thủ).
"""
import re, sqlite3, collections

B = 'file:C:/c/deepseek-harness/claw2-db/btchem.db?mode=ro'
TA = ['Bình Thạnh', 'BINH THANH', 'BTChem', 'Bình thạnh']
DUNG = ('sản xuất', 'chạy', 'không', 'chiếm', 'trong tuần', 'đang', 'và', 'có', 'tuần', 'này', 'thì', 'nhưng',
        'vẫn', 'đã', 'sẽ', 'giảm', 'tăng', 'dừng', 'bán', 'mới', 'cũ', 'đơn hàng', 'bộ', 'cont', 'm²', 'm2', '..', '.')
RE_TEN = re.compile(r'(?:sơn|NCC|Nhà cung cấp|ncc)\s+([^\s,;]+(?:\s+[^\s,;]+)?)', re.I)
RE_CONT = re.compile(r'([\d]+(?:[.,]\d+)?)\s*cont', re.I)
RE_PCT = re.compile(r'([\d]+(?:[.,]\d+)?)\s*%')


def ten_dt(doan):
    """Tách tên đối thủ trong 1 đoạn."""
    for m in RE_TEN.finditer(doan):
        ten = m.group(1).strip()
        # cắt phần đuôi là động từ/từ nối
        tu = ten.split()
        while tu and tu[-1].lower().strip('.,') in DUNG:
            tu.pop()
        ten = ' '.join(tu).strip(' .,-')
        if not ten or len(ten) < 2 or len(ten) > 28:
            continue
        if any(t.lower() in ten.lower() for t in TA):
            continue
        if ten.lower() in ('và', 'của', 'nhiều', 'các'):
            continue
        return ten
    return ''


def phan_tich(txt):
    """-> (danh sách đối thủ, tổng cont của đối thủ, % của mình nếu ghi)"""
    if not txt or not txt.strip():
        return [], 0.0, None
    ds, tong_cont, pct_minh = [], 0.0, None
    # tách theo dấu phẩy / xuống dòng, GIỮ đoạn chứa 'cont' hoặc '%'
    doan_all = re.split(r'[,;\n]|\.\s', txt)
    for doan in doan_all:
        d = doan.strip()
        if not d:
            continue
        if 'Bình Thạnh' in d or 'Bình thạnh' in d or 'Bình thanh' in d:
            pm = RE_PCT.search(d)
            if pm and ('chiếm' in d.lower() or '%' in d):
                try:
                    v = float(pm.group(1).replace(',', '.'))
                    pct_minh = v if pct_minh is None else max(pct_minh, v)
                except Exception:
                    pass
            continue
        t = ten_dt(d)
        if not t:
            continue
        ds.append(t)
        cm = RE_CONT.search(d)
        if cm:
            try:
                tong_cont += float(cm.group(1).replace(',', '.'))
            except Exception:
                pass
    # bỏ trùng tên nhưng giữ thứ tự
    ra = []
    for t in ds:
        if t.lower() not in [x.lower() for x in ra]:
            ra.append(t)
    return ra, round(tong_cont, 2), pct_minh


if __name__ == '__main__':
    b = sqlite3.connect(B, uri=True)
    dem_dt = collections.Counter()
    dem_nm = collections.Counter()
    cont_dt = collections.Counter()
    print('  --- TÁCH TỪNG NHÀ MÁY (tuần 41) ---')
    for r in b.execute("""select coalesce(n.ten,''), trim(coalesce(bc.canh_tranh,'')) from bao_cao_sx bc
                          left join nha_may n on n.id=bc.nha_may_id where bc.tuan='T41' order by n.ten"""):
        ds, cont, pct = phan_tich(r[1])
        if ds or cont:
            for t in ds:
                dem_dt[t] += 1
                dem_nm[t] += 1
            if cont:
                for t in ds:
                    cont_dt[t] += cont / max(len(ds), 1)
            print('    %-24s | %-38s | cont=%5.1f | mình %s%%' % (r[0][:24], ', '.join(ds)[:38], cont, pct if pct is not None else '—'))
    print('\n  --- ĐỐI THỦ theo số NHÀ MÁY (tuần 41) ---')
    for t, n in dem_dt.most_common(20):
        print('    %-22s %2d nhà máy | cont ước tính: %5.1f' % (t, n, cont_dt.get(t, 0)))
    print('\n  --- TỔNG cont đối thủ (tuần 41, chỉ nơi ghi số) ---')
    print('    tổng cont ghi trong ô cạnh tranh:', round(sum(cont_dt.values()), 1))
    # tổng hợp nhiều tuần
    print('\n  --- TOP đối thủ tính TOÀN BỘ 12 tuần (số lần xuất hiện) ---')
    dem_all = collections.Counter()
    for r in b.execute("select trim(coalesce(canh_tranh,'')) from bao_cao_sx"):
        ds, _, _ = phan_tich(r[0])
        for t in ds:
            dem_all[t] += 1
    for t, n in dem_all.most_common(20):
        print('    %-22s %3d lần' % (t, n))
    print('    TỔNG số đối thủ khác nhau:', len(dem_all))
