import openpyxl
import os
import glob
import sys
import re
from docx import Document
from docx.shared import Inches, Pt, RGBColor
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.enum.table import WD_TABLE_ALIGNMENT
from docx.oxml import parse_xml
from docx.oxml.ns import nsdecls

# Ensure standard output uses UTF-8
sys.stdout.reconfigure(encoding='utf-8')

# Brand colors
PRIMARY_COLOR = RGBColor(31, 78, 121)    # Deep Navy Blue
SECONDARY_COLOR = RGBColor(127, 127, 127) # Medium Gray
DARK_TEXT = RGBColor(51, 51, 51)         # Dark Gray (off-black)
LIGHT_BG_HEX = "F2F2F2"                  # Light Gray background for headers
PRIMARY_BG_HEX = "1F4E79"                # Hex Navy for cell fill

def set_cell_background(cell, fill_hex):
    """Set background color of a cell using XML parsing"""
    tcPr = cell._tc.get_or_add_tcPr()
    shd = parse_xml(f'<w:shd {nsdecls("w")} w:fill="{fill_hex}"/>')
    tcPr.append(shd)

def set_cell_margins(cell, top=100, bottom=100, left=150, right=150):
    """Set padding for a cell using XML parsing"""
    tcPr = cell._tc.get_or_add_tcPr()
    tcMar = parse_xml(f'<w:tcMar {nsdecls("w")}><w:top w:w="{top}" w:type="dxa"/><w:bottom w:w="{bottom}" w:type="dxa"/><w:left w:w="{left}" w:type="dxa"/><w:right w:w="{right}" w:type="dxa"/></w:tcMar>')
    tcPr.append(tcMar)

def create_styled_table(doc, rows, cols):
    """Create a table aligned in center with custom borders and style"""
    table = doc.add_table(rows=rows, cols=cols)
    table.alignment = WD_TABLE_ALIGNMENT.CENTER
    table.style = 'Table Grid'
    return table

def format_header_cell(cell, text):
    """Apply standard styling to header cells"""
    set_cell_background(cell, PRIMARY_BG_HEX)
    set_cell_margins(cell, top=120, bottom=120, left=150, right=150)
    p = cell.paragraphs[0]
    p.alignment = WD_ALIGN_PARAGRAPH.CENTER
    p.paragraph_format.space_before = Pt(4)
    p.paragraph_format.space_after = Pt(4)
    run = p.add_run(text)
    run.bold = True
    run.font.color.rgb = RGBColor(255, 255, 255)
    run.font.size = Pt(10.5)

def format_data_cell(cell, text, align=WD_ALIGN_PARAGRAPH.LEFT, bold=False, italic=False, bg_hex=None):
    """Apply styling to data cells"""
    if bg_hex:
        set_cell_background(cell, bg_hex)
    set_cell_margins(cell, top=90, bottom=90, left=120, right=120)
    p = cell.paragraphs[0]
    p.alignment = align
    p.paragraph_format.space_before = Pt(2)
    p.paragraph_format.space_after = Pt(2)
    run = p.add_run(str(text))
    run.bold = bold
    run.italic = italic
    run.font.color.rgb = DARK_TEXT
    run.font.size = Pt(9.5)

def main():
    da_lam_sach_dir = r"C:\antigra-DS\CLAW_LAM_VIEC\Bao cao - Hanh chinh\Bao cao lam mau\da lam sach"
    files = [f for f in sorted(glob.glob(os.path.join(da_lam_sach_dir, "*.xlsx"))) if "KT-GIOI" not in os.path.basename(f)]
    
    if len(files) < 4:
        print(f"Error: Found only {len(files)} files. Need at least 4 cleaned files to compare.")
        return
        
    files_to_compare = files[-4:]
    print("Files used for comparison:", [os.path.basename(f) for f in files_to_compare])
    
    weekly_data = []
    
    for file in files_to_compare:
        wb = openpyxl.load_workbook(file)
        ws = wb.active
        
        row1 = [ws.cell(1, col).value for col in range(1, 15)]
        row2 = [ws.cell(2, col).value for col in range(1, 15)]
        
        if row1[0] == 'Stt':
            start_row = 2
        elif row2[0] == 'Stt':
            start_row = 3
        else:
            start_row = 2
            
        filename = os.path.basename(file)
        week_num_match = re.search(r'Tuan_(\d+)', filename)
        week_num = f"Tuần {week_num_match.group(1)}" if week_num_match else "Chưa rõ"
        
        date_range_match = re.search(r'Tuan_\d+_(.*?)(?:_DA-LAM-SACH)?\.xlsx', filename)
        date_range = date_range_match.group(1).replace('_', ' ') if date_range_match else ""
        
        total_rows = 0
        total_qty = 0
        types = {'Mới': 0, 'Nhân': 0, 'Bộ': 0}
        statuses = {'HT': 0, 'DK': 0, 'ĐL': 0}
        factories = {}
        technicians = {}
        co_dh = 0
        
        for r in range(start_row, ws.max_row + 1):
            row_vals = [ws.cell(r, col).value for col in range(1, 15)]
            if all(x is None or str(x).strip() == '' for x in row_vals):
                continue
                
            nha_may = ws.cell(r, 2).value
            nha_may_str = str(nha_may).strip().upper() if nha_may else ""
            
            # ONLY KEEP TTF (Trường Thành)
            if not ("TTF" in nha_may_str or "TRƯỜNG THÀNH" in nha_may_str or "TRUONG THANH" in nha_may_str):
                continue
                
            total_rows += 1
            
            qty = ws.cell(r, 10).value
            loai = ws.cell(r, 8).value
            status = ws.cell(r, 12).value
            dh = ws.cell(r, 13).value
            tech = ws.cell(r, 11).value
            
            qty_val = 0
            if qty is not None:
                try:
                    qty_val = int(qty)
                    total_qty += qty_val
                except:
                    pass
            
            if nha_may:
                nha_may = str(nha_may).strip()
                factories[nha_may] = factories.get(nha_may, 0) + (qty_val if qty_val > 0 else 1)
                
            if loai in types:
                types[loai] += 1
            else:
                types['Khác'] = types.get('Khác', 0) + 1
                
            if status in statuses:
                statuses[status] += 1
            else:
                statuses['Khác'] = statuses.get('Khác', 0) + 1
                
            if dh == 'X' or dh == 'x':
                co_dh += 1
                
            if tech:
                tech = str(tech).strip()
                # Split multiple technicians
                for t in [p.strip() for p in re.split(r'[,+]+', tech)]:
                    if t:
                        technicians[t] = technicians.get(t, 0) + (qty_val if qty_val > 0 else 1)
                
        weekly_data.append({
            'week': week_num,
            'range': date_range,
            'rows': total_rows,
            'qty': total_qty,
            'types': types,
            'statuses': statuses,
            'co_dh': co_dh,
            'factories': sorted(factories.items(), key=lambda x: x[1], reverse=True),
            'technicians': sorted(technicians.items(), key=lambda x: x[1], reverse=True)
        })
        
    doc = Document()
    
    sections = doc.sections
    for section in sections:
        section.top_margin = Inches(1)
        section.bottom_margin = Inches(1)
        section.left_margin = Inches(1)
        section.right_margin = Inches(1)
        
    style_normal = doc.styles['Normal']
    style_normal.font.name = 'Calibri'
    style_normal.font.size = Pt(11)
    style_normal.font.color.rgb = DARK_TEXT
    
    # Document Title
    p_title = doc.add_paragraph()
    p_title.alignment = WD_ALIGN_PARAGRAPH.CENTER
    p_title.paragraph_format.space_before = Pt(24)
    p_title.paragraph_format.space_after = Pt(6)
    run_title = p_title.add_run("BÁO CÁO TIẾN ĐỘ LÀM MẪU — NHÀ MÁY TRƯỜNG THÀNH (TTF)")
    run_title.bold = True
    run_title.font.size = Pt(18)
    run_title.font.color.rgb = PRIMARY_COLOR
    
    # Subtitle
    p_sub = doc.add_paragraph()
    p_sub.alignment = WD_ALIGN_PARAGRAPH.CENTER
    p_sub.paragraph_format.space_after = Pt(24)
    run_sub = p_sub.add_run(f"ĐỐI CHIẾU VÀ SO SÁNH 4 TUẦN GẦN NHẤT\n({weekly_data[0]['week']} - {weekly_data[-1]['week']})")
    run_sub.italic = True
    run_sub.font.size = Pt(12)
    run_sub.font.color.rgb = SECONDARY_COLOR
    
    # Divider
    p_div = doc.add_paragraph()
    p_div.alignment = WD_ALIGN_PARAGRAPH.CENTER
    run_div = p_div.add_run("—" * 50)
    run_div.font.color.rgb = SECONDARY_COLOR
    
    # Section 1
    h1 = doc.add_paragraph()
    h1.paragraph_format.space_before = Pt(18)
    h1.paragraph_format.space_after = Pt(6)
    run_h1 = h1.add_run("1. TỔNG QUAN CHUNG (EXECUTIVE SUMMARY)")
    run_h1.bold = True
    run_h1.font.size = Pt(14)
    run_h1.font.color.rgb = PRIMARY_COLOR
    
    latest_week = weekly_data[-1]
    p_intro = doc.add_paragraph()
    p_intro.paragraph_format.line_spacing = 1.15
    p_intro.paragraph_format.space_after = Pt(10)
    p_intro.add_run(
        f"Báo cáo này tổng hợp dữ liệu làm mẫu của riêng nhà máy Trường Thành (TTF), phân tích tiến độ thực hiện và đối chiếu hiệu suất của "
        f"{latest_week['week']} ({latest_week['range']}) so với 3 tuần trước đó.\n\n"
        f"Trong tuần gần nhất ({latest_week['week']}), nhà máy Trường Thành (TTF) ghi nhận tổng số "
    )
    r_bold1 = p_intro.add_run(f"{latest_week['rows']} lượt mẫu ")
    r_bold1.bold = True
    p_intro.add_run("với tổng số lượng sản phẩm làm mẫu là ")
    r_bold2 = p_intro.add_run(f"{latest_week['qty']} cái. ")
    r_bold2.bold = True
    p_intro.add_run("Trong đó đã hoàn thành ")
    r_bold3 = p_intro.add_run(f"{latest_week['statuses'].get('HT', 0)} mẫu ")
    r_bold3.bold = True
    p_intro.add_run("và có ")
    r_bold4 = p_intro.add_run(f"{latest_week['statuses'].get('DK', 0)} mẫu đã ký. ")
    r_bold4.bold = True
    
    # Section 2: Table
    h2 = doc.add_paragraph()
    h2.paragraph_format.space_before = Pt(18)
    h2.paragraph_format.space_after = Pt(8)
    run_h2 = h2.add_run("2. BẢNG SO SÁNH TIẾN ĐỘ LÀM MẪU TTF QUA 4 TUẦN")
    run_h2.bold = True
    run_h2.font.size = Pt(14)
    run_h2.font.color.rgb = PRIMARY_COLOR
    
    headers = ["Chỉ số so sánh", weekly_data[0]['week'], weekly_data[1]['week'], weekly_data[2]['week'], weekly_data[3]['week']]
    table = create_styled_table(doc, rows=10, cols=5)
    
    for col_idx, text in enumerate(headers):
        format_header_cell(table.cell(0, col_idx), text)
        
    row_titles = [
        "Tổng số lượt mẫu (dòng)",
        "Tổng số lượng mẫu (cái)",
        "Số lượng mẫu Mới",
        "Số lượng mẫu Nhân",
        "Số lượng mẫu Bộ (sản phẩm)",
        "Số mẫu Hoàn thành (HT)",
        "Số mẫu Đã Ký (DK)",
        "Số mẫu Đang làm (ĐL)",
        "Mẫu có Đơn hàng ký kết (Có ĐH)"
    ]
    
    for r_idx, title in enumerate(row_titles, 1):
        cell_title = table.cell(r_idx, 0)
        format_data_cell(cell_title, title, bold=True)
        
        for w_idx, w_data in enumerate(weekly_data):
            cell = table.cell(r_idx, w_idx + 1)
            val = 0
            if r_idx == 1:
                val = w_data['rows']
            elif r_idx == 2:
                val = w_data['qty']
            elif r_idx == 3:
                val = w_data['types'].get('Mới', 0)
            elif r_idx == 4:
                val = w_data['types'].get('Nhân', 0)
            elif r_idx == 5:
                val = w_data['types'].get('Bộ', 0)
            elif r_idx == 6:
                val = w_data['statuses'].get('HT', 0)
            elif r_idx == 7:
                val = w_data['statuses'].get('DK', 0)
            elif r_idx == 8:
                val = w_data['statuses'].get('ĐL', 0)
            elif r_idx == 9:
                val = w_data['co_dh']
            
            format_data_cell(cell, val, align=WD_ALIGN_PARAGRAPH.CENTER)
            
    for r_idx in range(1, 10):
        if r_idx % 2 == 0:
            for col_idx in range(5):
                set_cell_background(table.cell(r_idx, col_idx), LIGHT_BG_HEX)
                
    p_note = doc.add_paragraph()
    p_note.paragraph_format.space_before = Pt(8)
    p_note.paragraph_format.space_after = Pt(12)
    run_note = p_note.add_run("*Nhận xét xu hướng: ")
    run_note.bold = True
    run_note.font.italic = True
    
    q_diff = latest_week['qty'] - weekly_data[-2]['qty']
    trend_txt = f"Sản lượng mẫu của nhà máy Trường Thành (TTF) duy trì ổn định. Trong tuần 29 ghi nhận {latest_week['rows']} lượt mẫu với {latest_week['statuses'].get('HT', 0)} mẫu hoàn thành (HT) và {latest_week['statuses'].get('DK', 0)} mẫu đã ký (DK) báo giá gửi về công ty."
    p_note.add_run(trend_txt).font.italic = True
    
    # Section 3
    h3 = doc.add_paragraph()
    h3.paragraph_format.space_before = Pt(18)
    h3.paragraph_format.space_after = Pt(8)
    run_h3 = h3.add_run(f"3. PHÂN TÍCH CHI TIẾT KỸ THUẬT VIÊN TRONG {latest_week['week']}")
    run_h3.bold = True
    run_h3.font.size = Pt(14)
    run_h3.font.color.rgb = PRIMARY_COLOR
    
    p_tech = doc.add_paragraph()
    p_tech.paragraph_format.space_before = Pt(6)
    p_tech.paragraph_format.space_after = Pt(4)
    run_tech_title = p_tech.add_run("Kỹ Thuật Viên phụ trách chính:")
    run_tech_title.bold = True
    
    # KTV Table
    tech_table = create_styled_table(doc, rows=len(latest_week['technicians']) + 1 if latest_week['technicians'] else 2, cols=3)
    format_header_cell(tech_table.cell(0, 0), "Hạng")
    format_header_cell(tech_table.cell(0, 1), "Kỹ Thuật Viên")
    format_header_cell(tech_table.cell(0, 2), "Sản lượng làm mẫu (cái)")
    
    if not latest_week['technicians']:
        format_data_cell(tech_table.cell(1, 0), "-", align=WD_ALIGN_PARAGRAPH.CENTER)
        format_data_cell(tech_table.cell(1, 1), "-")
        format_data_cell(tech_table.cell(1, 2), "-", align=WD_ALIGN_PARAGRAPH.CENTER)
    else:
        for i, (name, qty) in enumerate(latest_week['technicians']):
            r_idx = i + 1
            format_data_cell(tech_table.cell(r_idx, 0), i+1, align=WD_ALIGN_PARAGRAPH.CENTER)
            format_data_cell(tech_table.cell(r_idx, 1), name)
            format_data_cell(tech_table.cell(r_idx, 2), qty, align=WD_ALIGN_PARAGRAPH.CENTER)
            
    for r_idx in range(1, len(latest_week['technicians']) + 1):
        if r_idx % 2 == 0:
            for col_idx in range(3):
                set_cell_background(tech_table.cell(r_idx, col_idx), LIGHT_BG_HEX)
                
    output_dir = r"C:\antigra-DS\CLAW_LAM_VIEC\Bao cao - Hanh chinh\Bao cao lam mau\Bao cao"
    os.makedirs(output_dir, exist_ok=True)
    start_wk = weekly_data[0]['week'].replace("Tuần ", "").strip()
    end_wk = weekly_data[-1]['week'].replace("Tuần ", "").strip()
    output_path = os.path.join(output_dir, f"Bao_cao_tien_do_lam_mau_TTF_tuan_{start_wk}_{end_wk}.docx")
    doc.save(output_path)
    print(f"Report generated successfully: {output_path}")

if __name__ == "__main__":
    main()
