# -*- coding: utf-8 -*-
"""Quet TAT CA bao cao tong hop tuan: NCC/doi thu nao xuat hien o tuan nao, nha may nao."""
import glob, os, re
from docx import Document

ROOTS = [r"C:\Claw 2\Bao cao - Hanh chinh\Dac-Phai-VIen-KT\Bao-Cao-Tuan",
         r"C:\Claw 2\Bao cao - Hanh chinh\BAOCAOTONGHOP",
         r"C:\Users\admin\AppData\Local\hermes\cache\documents"]

NAMES = ["AkzoNobel", "MTH", "Syncoat", "Tân Hồng Phát", "Poly Poxy", "Brochem", "Visan", "Xinpan",
         "Jotun", "Teknos", "Sayerlack", "Nippon", "Wang", "Sato", "Đại Phát", "Hoàng Gia", "Kim Sơn", "Musashi", "Toyo", "Wanhua", "Sherwin", "PPG"]

files = []
for r in ROOTS:
    for f in glob.glob(os.path.join(r, "**", "Bao_cao_tong_hop_Tuan*.docx"), recursive=True):
        if "_cu" in f or ".bak_" in f:
            continue
        files.append(f)
for f in glob.glob(os.path.join(ROOTS[2], "*Bao_cao_tong_hop_Tuan*.docx")):
    files.append(f)

def tuan_of(path):
    m = re.search(r"Tuan\s*(\d+)", os.path.basename(path)) or re.search(r"T(\d+)", os.path.basename(path))
    return int(m.group(1)) if m else 0

seen = set()
rows = []
for f in sorted(files, key=tuan_of):
    key = (tuan_of(f), os.path.basename(f))
    if key in seen:
        continue
    seen.add(key)
    try:
        d = Document(f)
    except Exception as e:
        print("loi doc", f, e); continue
    txt = "\n".join(x.text for x in d.paragraphs) + "\n" + "\n".join(
        " | ".join(c.text for c in r.cells) for t in d.tables for r in t.rows)
    found = {n: len(re.findall(re.escape(n), txt, re.I)) for n in NAMES}
    found = {k: v for k, v in found.items() if v}
    # nha may di kem MTH / Visan / Syncoat / Brochem
    ctx = {}
    for n in ["MTH", "Visan", "Syncoat", "Brochem", "AkzoNobel"]:
        s = set()
        for m in re.finditer(re.escape(n), txt, re.I):
            seg = txt[max(0, m.start()-160):m.start()+160]
            for nm in ["Hạnh Phúc", "Đăng Long", "Mekong 1", "Mekong 3", "Tân Việt Tiến", "Liên Minh",
                       "An Cường", "Đất Mới", "Minh Hưng Tiến", "Kim Huy", "Kim Phong", "Bảo Hưng",
                       "Thiết Đan", "Geuther", "Demeyer", "Hố Nai", "Anh Khoa", "Minh Dương", "Trường Thành", "Scandia"]:
                if nm in seg:
                    s.add(nm)
        if s:
            ctx[n] = sorted(s)
    rows.append((tuan_of(f), os.path.basename(f)[:60], found, ctx))

print("%-6s %-58s %s" % ("TUAN", "FILE", "NCC/DOI THU (so lan)"))
for t, name, found, ctx in rows:
    print("T%-5d %-58s %s" % (t, name, found))
print("\n--- NHA MAY DI KEM TUNG DOI THU ---")
for t, name, found, ctx in rows:
    if ctx:
        print("T%-4d %s" % (t, ctx))
