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():
    base_dir = os.path.dirname(os.path.abspath(__file__))
    da_lam_sach_dir = os.path.join(base_dir, "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) and "File1" not in os.path.basename(f) and "File2" not in os.path.basename(f) and "File3" 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
        
    # We will look at the 4 latest files.
    # In case there are more than 4, take the last 4.
    files_to_compare = files[-4:]
    print("Files used for comparison:", [os.path.basename(f) for f in files_to_compare])
    
    weekly_data = []
    
    # Process each of the 4 files
    for file in files_to_compare:
        wb = openpyxl.load_workbook(file)
        ws = wb.active
        
        # Decide starting row
        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
            
        # Extract metadata from name
        # Format e.g., Tuan_24_08-14.06_DA-LAM-SACH.xlsx
        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 ""
        # Clean date range formatting (e.g. "08-14.06" -> "08/06 - 14/06/2026")
        
        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
                
            total_rows += 1
            
            nha_may = ws.cell(r, 2).value
            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()
                technicians[tech] = technicians.get(tech, 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)
        })
        
    # Start creating the Word Document
    doc = Document()
    
    # Configure page margins
    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)
        
    # Styles config
    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")
    run_title.bold = True
    run_title.font.size = Pt(20)
    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
    
    # Horizontal Divider Line
    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: Executive Summary
    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 từ các nhà máy, 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 đó. Mục tiêu nhằm theo dõi xu hướng phát triển mẫu, "
        f"đánh giá năng lực của các kỹ thuật viên, nhà máy và tỷ lệ chuyển đổi đơn hàng thành công.\n\n"
        f"Trong tuần gần nhất ({latest_week['week']}), hệ thống 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("Tỷ lệ hoàn thành đạt mức ấn tượng với ")
    r_bold3 = p_intro.add_run(f"{latest_week['statuses'].get('HT', 0)} mẫu hoàn thành ")
    r_bold3.bold = True
    p_intro.add_run("(chiếm tỷ lệ cao trong tổng thể).")
    
    # Section 2: 4-Week Comparison 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 4 TUẦN")
    run_h2.bold = True
    run_h2.font.size = Pt(14)
    run_h2.font.color.rgb = PRIMARY_COLOR
    
    # Table Comparison
    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)
    
    # Format Headers
    for col_idx, text in enumerate(headers):
        format_header_cell(table.cell(0, col_idx), text)
        
    # Table rows definitions
    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)"
    ]
    
    # Fill Table
    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 = None
            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)
            
    # Style the alternating columns or rows
    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
    
    # Generate some dynamic comparison insights
    q_diff = latest_week['qty'] - weekly_data[-2]['qty']
    trend_txt = f"Số lượng sản phẩm làm mẫu đạt đỉnh vào tuần 26 ({weekly_data[-2]['qty']} cái), nhờ có đóng góp lớn từ nhà máy HẠNH PHÚC. Tuần 27 giảm nhẹ {abs(q_diff)} cái nhưng vẫn duy trì ở mức cao ({latest_week['qty']} cái) và có số lượng mẫu hoàn thành (HT) cao nhất trong 4 tuần qua với {latest_week['statuses'].get('HT', 0)} mẫu."
    p_note.add_run(trend_txt).font.italic = True
    
    # Section 3: Detailed Breakdown for Latest Week
    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 HIỆU SUẤT TRONG {latest_week['week']}")
    run_h3.bold = True
    run_h3.font.size = Pt(14)
    run_h3.font.color.rgb = PRIMARY_COLOR
    
    # Top Factories Table
    p_fac = doc.add_paragraph()
    p_fac.paragraph_format.space_before = Pt(6)
    p_fac.paragraph_format.space_after = Pt(4)
    run_fac_title = p_fac.add_run("Top Nhà Máy có số lượng làm mẫu lớn nhất:")
    run_fac_title.bold = True
    
    fac_table = create_styled_table(doc, rows=6, cols=3)
    format_header_cell(fac_table.cell(0, 0), "Hạng")
    format_header_cell(fac_table.cell(0, 1), "Nhà Máy")
    format_header_cell(fac_table.cell(0, 2), "Số lượng mẫu sản xuất (cái)")
    
    for i in range(5):
        r_idx = i + 1
        format_data_cell(fac_table.cell(r_idx, 0), i+1, align=WD_ALIGN_PARAGRAPH.CENTER)
        if i < len(latest_week['factories']):
            name, qty = latest_week['factories'][i]
            format_data_cell(fac_table.cell(r_idx, 1), name)
            format_data_cell(fac_table.cell(r_idx, 2), qty, align=WD_ALIGN_PARAGRAPH.CENTER)
        else:
            format_data_cell(fac_table.cell(r_idx, 1), "-")
            format_data_cell(fac_table.cell(r_idx, 2), "-", align=WD_ALIGN_PARAGRAPH.CENTER)
            
    for r_idx in range(1, 6):
        if r_idx % 2 == 0:
            for col_idx in range(3):
                set_cell_background(fac_table.cell(r_idx, col_idx), LIGHT_BG_HEX)
                
    # Top Technicians Table
    p_tech = doc.add_paragraph()
    p_tech.paragraph_format.space_before = Pt(12)
    p_tech.paragraph_format.space_after = Pt(4)
    run_tech_title = p_tech.add_run("Top Kỹ Thuật Viên hoạt động tích cực nhất:")
    run_tech_title.bold = True
    
    tech_table = create_styled_table(doc, rows=6, 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 (Đã chuẩn hóa)")
    format_header_cell(tech_table.cell(0, 2), "Sản lượng làm mẫu (cái)")
    
    for i in range(5):
        r_idx = i + 1
        format_data_cell(tech_table.cell(r_idx, 0), i+1, align=WD_ALIGN_PARAGRAPH.CENTER)
        if i < len(latest_week['technicians']):
            name, qty = latest_week['technicians'][i]
            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)
        else:
            format_data_cell(tech_table.cell(r_idx, 1), "-")
            format_data_cell(tech_table.cell(r_idx, 2), "-", align=WD_ALIGN_PARAGRAPH.CENTER)
            
    for r_idx in range(1, 6):
        if r_idx % 2 == 0:
            for col_idx in range(3):
                set_cell_background(tech_table.cell(r_idx, col_idx), LIGHT_BG_HEX)
                
    # Section 4: Process Improvement & Action Items
    h4 = doc.add_paragraph()
    h4.paragraph_format.space_before = Pt(18)
    h4.paragraph_format.space_after = Pt(8)
    run_h4 = h4.add_run("4. CẢI TIẾN QUY TRÌNH & ĐỀ XUẤT")
    run_h4.bold = True
    run_h4.font.size = Pt(14)
    run_h4.font.color.rgb = PRIMARY_COLOR
    
    p_prop = doc.add_paragraph(style='List Bullet')
    p_prop.paragraph_format.space_after = Pt(4)
    run_bullet1_bold = p_prop.add_run("Chuẩn hóa nhập liệu: ")
    run_bullet1_bold.bold = True
    p_prop.add_run(
        "Kích hoạt và triển khai skill làm sạch tự động dữ liệu nhằm hạn chế tối đa các biến thể tên viết sai lỗi chính tả "
        "từ phía các nhà máy (như Trần Dũng, Nguyễn Hữu Lợi, V. Thưởng). Đảm bảo tính nhất quán trên hệ thống báo cáo."
    )
    
    p_prop2 = doc.add_paragraph(style='List Bullet')
    p_prop2.paragraph_format.space_after = Pt(4)
    run_bullet2_bold = p_prop2.add_run("Rà soát tiến độ trễ: ")
    run_bullet2_bold.bold = True
    p_prop2.add_run(
        "Mặc dù số mẫu Hoàn thành (HT) ở mức cao, cần giám sát chặt chẽ các mẫu đang trong trạng thái Đang làm (ĐL) "
        "kéo dài qua nhiều tuần để tháo gỡ khó khăn về nguyên vật liệu kịp thời."
    )
    
    p_prop3 = doc.add_paragraph(style='List Bullet')
    p_prop3.paragraph_format.space_after = Pt(12)
    run_bullet3_bold = p_prop3.add_run("Khuyến khích chuyển đổi đơn hàng: ")
    run_bullet3_bold.bold = True
    p_prop3.add_run(
        "Tăng cường theo dõi các mẫu có ghi nhận đơn hàng ký kết để rút ra bài học kinh nghiệm từ các mẫu phát triển thành công."
    )
    
    # Save Report
    output_dir = os.path.join(base_dir, "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_tuan_{start_wk}_{end_wk}.docx")
    doc.save(output_path)
    print(f"Report generated successfully: {output_path}")

if __name__ == "__main__":
    main()
