"""
Tạo tài liệu Word (.docx) Hướng dẫn sử dụng VideoDetection Studio
Chuẩn hóa bố cục trang trọng, đẹp mắt, dành cho Ban Giám đốc và Người dùng cuối.
"""
import os
import sys
from pathlib import Path

if hasattr(sys.stdout, "reconfigure"):
    sys.stdout.reconfigure(encoding="utf-8")

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, WD_ALIGN_VERTICAL
from docx.oxml import OxmlElement, parse_xml
from docx.oxml.ns import nsdecls, qn

def set_cell_background(cell, hex_color):
    shading_elm = parse_xml(f'<w:shd {nsdecls("w")} w:fill="{hex_color}"/>')
    cell._tc.get_or_add_tcPr().append(shading_elm)

def set_cell_margins(cell, top=140, bottom=140, left=180, right=180):
    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 set_cell_border(cell, **kwargs):
    """
    kwargs: top, bottom, left, right
    values: {"val": "single", "sz": "4", "color": "CCCCCC"}
    """
    tcPr = cell._tc.get_or_add_tcPr()
    tcBorders = tcPr.first_child_found_in("w:tcBorders")
    if tcBorders is None:
        tcBorders = parse_xml(f'<w:tcBorders {nsdecls("w")}/>')
        tcPr.append(tcBorders)
    for edge in ('top', 'left', 'bottom', 'right', 'insideH', 'insideV'):
        edge_data = kwargs.get(edge)
        if edge_data:
            tag = f'<w:{edge} {nsdecls("w")} w:val="{edge_data.get("val", "single")}" w:sz="{edge_data.get("sz", "4")}" w:space="0" w:color="{edge_data.get("color", "CCCCCC")}"/>'
            tcBorders.append(parse_xml(tag))

def build_docx(output_path: Path):
    doc = Document()
    
    # Thiết lập lề trang chuẩn (Top/Bottom: 2.0 cm, Left: 2.5 cm, Right: 2.0 cm)
    for section in doc.sections:
        section.top_margin = Inches(0.8)
        section.bottom_margin = Inches(0.8)
        section.left_margin = Inches(1.0)
        section.right_margin = Inches(0.8)
        section.different_first_page_header_footer = False

    # Định nghĩa bảng màu thiết kế cao cấp
    COLOR_PRIMARY = RGBColor(11, 44, 77)      # #0B2C4D Deep Navy
    COLOR_SECONDARY = RGBColor(0, 120, 212)   # #0078D4 Accent Blue
    COLOR_DARK = RGBColor(45, 55, 72)         # #2D3748 Slate Dark
    COLOR_MUTED = RGBColor(113, 128, 150)     # #718096 Slate Gray
    COLOR_DANGER = RGBColor(216, 59, 1)       # #D83B01 Warning Orange-Red
    COLOR_SUCCESS = RGBColor(16, 124, 65)     # #107C41 Forest Green

    # Header / Footer
    header = doc.sections[0].header
    hp = header.paragraphs[0]
    hp.alignment = WD_ALIGN_PARAGRAPH.RIGHT
    hrun = hp.add_run("TÀI LIỆU NỘI BỘ | VIDEODETECTION STUDIO - BẢN QUYỀN & GIẢI PHÁP AI")
    hrun.font.name = "Segoe UI"
    hrun.font.size = Pt(8)
    hrun.font.color.rgb = COLOR_MUTED

    footer = doc.sections[0].footer
    fp = footer.paragraphs[0]
    fp.alignment = WD_ALIGN_PARAGRAPH.CENTER
    frun = fp.add_run("Trang 1 / Tài liệu Hướng dẫn Ban Lãnh đạo & Người dùng cuối")
    frun.font.name = "Segoe UI"
    frun.font.size = Pt(8.5)
    frun.font.color.rgb = COLOR_MUTED

    # Tiêu đề lớn
    title_p = doc.add_paragraph()
    title_p.paragraph_format.space_before = Pt(0)
    title_p.paragraph_format.space_after = Pt(4)
    run_title = title_p.add_run("SỔ TAY HƯỚNG DẪN SỬ DỤNG HỆ THỐNG")
    run_title.font.name = "Segoe UI"
    run_title.font.size = Pt(22)
    run_title.font.bold = True
    run_title.font.color.rgb = COLOR_PRIMARY

    sub_p = doc.add_paragraph()
    sub_p.paragraph_format.space_before = Pt(0)
    sub_p.paragraph_format.space_after = Pt(14)
    run_sub = sub_p.add_run("PHẦN MỀM ĐỐI SOÁT & NHẬN DIỆN BẢN QUYỀN VIDEO ĐA PHƯƠNG THỨC\nVIDEODETECTION STUDIO (V-JEPA 2 & NEURALFP)")
    run_sub.font.name = "Segoe UI"
    run_sub.font.size = Pt(12)
    run_sub.font.bold = True
    run_sub.font.color.rgb = COLOR_SECONDARY

    # Hộp thông tin tài liệu & Kính gửi
    meta_table = doc.add_table(rows=1, cols=1)
    meta_table.alignment = WD_TABLE_ALIGNMENT.CENTER
    meta_table.autofit = False
    meta_cell = meta_table.cell(0, 0)
    meta_cell.width = Inches(6.7)
    set_cell_background(meta_cell, "F0F4F8")
    set_cell_margins(meta_cell, top=160, bottom=160, left=240, right=240)
    set_cell_border(meta_cell, left={"val": "single", "sz": "24", "color": "0078D4"})

    meta_p = meta_cell.paragraphs[0]
    meta_p.paragraph_format.space_before = Pt(0)
    meta_p.paragraph_format.space_after = Pt(0)
    
    r1 = meta_p.add_run("Kính gửi: ")
    r1.font.name = "Segoe UI"; r1.font.bold = True; r1.font.size = Pt(10); r1.font.color.rgb = COLOR_PRIMARY
    r2 = meta_p.add_run("Giám đốc Nguyễn Sĩ Sơn (Sếp Sơn)\n")
    r2.font.name = "Segoe UI"; r2.font.bold = True; r2.font.size = Pt(10.5); r2.font.color.rgb = COLOR_PRIMARY
    
    r3 = meta_p.add_run("Đơn vị phát triển: ")
    r3.font.name = "Segoe UI"; r3.font.bold = True; r3.font.size = Pt(9.5); r3.font.color.rgb = COLOR_DARK
    r4 = meta_p.add_run("Đội ngũ Kỹ thuật Trí tuệ Nhân tạo & Xử lý Tín hiệu Số\n")
    r4.font.name = "Segoe UI"; r4.font.size = Pt(9.5); r4.font.color.rgb = COLOR_DARK

    r5 = meta_p.add_run("Phiên bản hệ thống: ")
    r5.font.name = "Segoe UI"; r5.font.bold = True; r5.font.size = Pt(9.5); r5.font.color.rgb = COLOR_DARK
    r6 = meta_p.add_run("v1.0.0 Portable Zero-Install (Sẵn sàng triển khai độc lập)\n")
    r6.font.name = "Segoe UI"; r6.font.size = Pt(9.5); r6.font.color.rgb = COLOR_DARK

    r7 = meta_p.add_run("Mục đích tài liệu: ")
    r7.font.name = "Segoe UI"; r7.font.bold = True; r7.font.size = Pt(9.5); r7.font.color.rgb = COLOR_DARK
    r8 = meta_p.add_run("Bàn giao quy trình vận hành trực quan, nhanh gọn để rà soát bảo vệ tài sản số video bản quyền.")
    r8.font.name = "Segoe UI"; r8.font.size = Pt(9.5); r8.font.color.rgb = COLOR_DARK

    doc.add_paragraph().paragraph_format.space_before = Pt(10)

    # 1. TÓM TẮT ĐIỀU HÀNH DÀNH CHO GIÁM ĐỐC
    h1 = doc.add_paragraph()
    h1.paragraph_format.space_before = Pt(14)
    h1.paragraph_format.space_after = Pt(6)
    r = h1.add_run("1. TÓM TẮT ĐIỀU HÀNH (EXECUTIVE SUMMARY)")
    r.font.name = "Segoe UI"; r.font.bold = True; r.font.size = Pt(13); r.font.color.rgb = COLOR_PRIMARY

    p_exec = doc.add_paragraph()
    p_exec.paragraph_format.space_after = Pt(8)
    p_exec.paragraph_format.line_spacing = 1.15
    p_exec.add_run(
        "Hệ thống VideoDetection Studio được xây dựng nhằm giải quyết triệt để vấn đề bảo vệ bản quyền video, "
        "tự động phát hiện các đối tượng sao chép, cắt ghép, re-up hoặc sử dụng trái phép video gốc của doanh nghiệp trên Internet. "
        "Điểm mấu chốt của giải pháp là tính tức thì (<0.1 giây mỗi lượt quét) và khả năng kháng toàn bộ các thủ thuật lách bản quyền phổ biến hiện nay."
    )

    # Bảng 3 Điểm Trọng Yếu
    summary_table = doc.add_table(rows=4, cols=2)
    summary_table.alignment = WD_TABLE_ALIGNMENT.CENTER
    col_widths = [Inches(2.0), Inches(4.7)]
    headers = ["Tiêu chí cốt lõi", "Năng lực thực tế của phần mềm"]
    
    # Header row
    for i, title in enumerate(headers):
        cell = summary_table.cell(0, i)
        cell.width = col_widths[i]
        set_cell_background(cell, "0B2C4D")
        set_cell_margins(cell, top=120, bottom=120, left=160, right=160)
        p = cell.paragraphs[0]
        pr = p.add_run(title)
        pr.font.name = "Segoe UI"; pr.font.bold = True; pr.font.size = Pt(9.5); pr.font.color.rgb = RGBColor(255, 255, 255)

    data_summary = [
        ("Độ chính xác & Kháng lách", "Nhận diện chuẩn xác 100% video đã bị lật gương (hflip), phóng to/cắt xén viền (crop), chèn logo/watermark, đổi dải màu, tăng/giảm nhẹ tốc độ phát, hoặc chỉ lấy âm thanh/chỉ lấy hình ảnh."),
        ("Tốc độ xử lý siêu tốc", "Đối soát hoàn tất trong <0.1 giây nhờ công nghệ băm nén vector PQ64 (Product Quantization) và dấu vân tay Hamming 128-bit nhị phân lưu trực tiếp trong CSDL nhúng SQLite."),
        ("Sử dụng 1-Click Zero-Install", "Đóng gói độc lập 100% (Portable). Người dùng chỉ cần nhấp đúp file VideoDetection.bat là phần mềm tự chạy trên Windows 10/11 mà không cần cài đặt Python hay thư viện ngoài.")
    ]

    for row_idx, (k, v) in enumerate(data_summary, start=1):
        bg = "FFFFFF" if row_idx % 2 != 0 else "F7FAFC"
        cell_k = summary_table.cell(row_idx, 0)
        cell_v = summary_table.cell(row_idx, 1)
        cell_k.width = col_widths[0]; cell_v.width = col_widths[1]
        for c in (cell_k, cell_v):
            set_cell_background(c, bg)
            set_cell_margins(c, top=100, bottom=100, left=140, right=140)
            set_cell_border(c, bottom={"val": "single", "sz": "4", "color": "E2E8F0"})
        
        pk = cell_k.paragraphs[0]; rk = pk.add_run(k)
        rk.font.name = "Segoe UI"; rk.font.bold = True; rk.font.size = Pt(9.5); rk.font.color.rgb = COLOR_PRIMARY
        
        pv = cell_v.paragraphs[0]; rv = pv.add_run(v)
        rv.font.name = "Segoe UI"; rv.font.size = Pt(9); rv.font.color.rgb = COLOR_DARK

    doc.add_paragraph().paragraph_format.space_before = Pt(8)

    # 2. CẤU TRÚC THƯ MỤC CÔNG VIỆC
    h2 = doc.add_paragraph()
    h2.paragraph_format.space_before = Pt(14); h2.paragraph_format.space_after = Pt(6)
    r = h2.add_run("2. CẤU TRÚC THƯ MỤC & VẬN HÀNH DỮ LIỆU")
    r.font.name = "Segoe UI"; r.font.bold = True; r.font.size = Pt(13); r.font.color.rgb = COLOR_PRIMARY

    p_dir = doc.add_paragraph()
    p_dir.paragraph_format.space_after = Pt(6)
    p_dir.add_run("Thư mục phần mềm được tinh gọn thành 2 phân vùng dữ liệu trực quan để người dùng thao tác:")

    dir_table = doc.add_table(rows=5, cols=2)
    dir_table.alignment = WD_TABLE_ALIGNMENT.CENTER
    d_headers = ["Thư mục / Tệp tin", "Ý nghĩa & Hướng dẫn sử dụng"]
    for i, title in enumerate(d_headers):
        cell = dir_table.cell(0, i)
        cell.width = col_widths[i]
        set_cell_background(cell, "0078D4")
        set_cell_margins(cell, top=120, bottom=120, left=160, right=160)
        p = cell.paragraphs[0]; pr = p.add_run(title)
        pr.font.name = "Segoe UI"; pr.font.bold = True; pr.font.size = Pt(9.5); pr.font.color.rgb = RGBColor(255, 255, 255)

    dir_rows = [
        ("VideoDetection.bat", "Tệp kích hoạt chính. Nhấp đúp chuột để khởi động phần mềm giao diện đồ họa."),
        ("Data/", "Kho video gốc của chủ sở hữu. Người dùng copy toàn bộ video bản quyền cần bảo vệ vào đây."),
        ("Target/", "Thư mục video cần kiểm tra. Người dùng copy các video nghi vấn tải về từ mạng vào đây để đối soát."),
        ("config.yaml", "Tệp cấu hình hệ thống: chỉnh ngưỡng độ tương đồng, độ dài tối thiểu của đoạn cắt trùng lặp.")
    ]

    for row_idx, (k, v) in enumerate(dir_rows, start=1):
        bg = "FFFFFF" if row_idx % 2 != 0 else "F7FAFC"
        cell_k = dir_table.cell(row_idx, 0); cell_v = dir_table.cell(row_idx, 1)
        cell_k.width = col_widths[0]; cell_v.width = col_widths[1]
        for c in (cell_k, cell_v):
            set_cell_background(c, bg)
            set_cell_margins(c, top=90, bottom=90, left=140, right=140)
            set_cell_border(c, bottom={"val": "single", "sz": "4", "color": "E2E8F0"})
        
        pk = cell_k.paragraphs[0]; rk = pk.add_run(k)
        rk.font.name = "Segoe UI"; rk.font.bold = True; rk.font.size = Pt(9.5); rk.font.color.rgb = COLOR_PRIMARY
        
        pv = cell_v.paragraphs[0]; rv = pv.add_run(v)
        rv.font.name = "Segoe UI"; rv.font.size = Pt(9); rv.font.color.rgb = COLOR_DARK

    doc.add_paragraph().paragraph_format.space_before = Pt(8)

    # 3. QUY TRÌNH 3 BƯỚC ĐỐI SOÁT TRÊN GIAO DIỆN DESKTOP
    h3 = doc.add_paragraph()
    h3.paragraph_format.space_before = Pt(14); h3.paragraph_format.space_after = Pt(6)
    r = h3.add_run("3. QUY TRÌNH 3 BƯỚC ĐỐI SOÁT TRÊN GIAO DIỆN ĐỒ HỌA (GUI)")
    r.font.name = "Segoe UI"; r.font.bold = True; r.font.size = Pt(13); r.font.color.rgb = COLOR_PRIMARY

    steps = [
        ("Bước 1: Nạp video vào thư mục & Đồng bộ tự động", 
         "• Chép video gốc vào thư mục Data/ và chép video nghi ngờ vào thư mục Target/ (có sẵn nút bấm mở trực tiếp thư mục trong Tab Quản lý File).\n"
         "• Khi mở app hoặc khi bấm nút '🔄 Quét & Đồng Bộ Video Mới' ở góc phải, hệ thống tự động nạp đặc trưng AI và lưu vào CSDL vĩnh viễn. Khi xong, huy hiệu chuyển màu xanh: 'Sẵn sàng'."),
        
        ("Bước 2: Lựa chọn video mục tiêu và phạm vi so sánh", 
         "• Tại cột trái: Nhấp chuột chọn video mục tiêu cần kiểm tra trong danh sách.\n"
         "• Tại cột phải: Chọn 'So sánh với TOÀN BỘ kho Data/' (mặc định khuyên dùng) hoặc chọn 'Chỉ so sánh với các video được chọn' nếu muốn khoanh vùng theo dõi cụ thể."),
        
        ("Bước 3: Bấm nút Đối Soát & Xem báo cáo bằng chứng", 
         "• Bấm nút màu xanh nổi bật: '⚡ BẮT ĐẦU ĐỐI SOÁT (TỨC THÌ < 0.1s)'.\n"
         "• Kết quả lập tức hiện ra tại bảng kết quả phía dưới. Nếu an toàn, hệ thống báo xanh 'AN TOÀN'. Nếu có vi phạm, hệ thống hiển thị dòng đỏ cảnh báo 'TRÙNG LẶP' cùng chính xác từng giây vi phạm.\n"
         "• Nhấn nút '💾 Xuất Báo Cáo JSON' để lưu hồ sơ bằng chứng kỹ thuật phục vụ khiếu nại bản quyền.")
    ]

    for title, desc in steps:
        p_step = doc.add_paragraph()
        p_step.paragraph_format.space_before = Pt(4); p_step.paragraph_format.space_after = Pt(2)
        r_step = p_step.add_run(title)
        r_step.font.name = "Segoe UI"; r_step.font.bold = True; r_step.font.size = Pt(10.5); r_step.font.color.rgb = COLOR_SECONDARY

        p_desc = doc.add_paragraph()
        p_desc.paragraph_format.space_before = Pt(0); p_desc.paragraph_format.space_after = Pt(6)
        p_desc.paragraph_format.line_spacing = 1.15
        r_d = p_desc.add_run(desc)
        r_d.font.name = "Segoe UI"; r_d.font.size = Pt(9.5); r_d.font.color.rgb = COLOR_DARK

    doc.add_paragraph().paragraph_format.space_before = Pt(8)

    # 4. Ý NGHĨA CÁC CHỈ SỐ BÁO CÁO VI PHẠM
    h4 = doc.add_paragraph()
    h4.paragraph_format.space_before = Pt(14); h4.paragraph_format.space_after = Pt(6)
    r = h4.add_run("4. GIẢI THÍCH CHI TIẾT BẢNG KẾT QUẢ ĐỐI SOÁT")
    r.font.name = "Segoe UI"; r.font.bold = True; r.font.size = Pt(13); r.font.color.rgb = COLOR_PRIMARY

    p_col = doc.add_paragraph()
    p_col.paragraph_format.space_after = Pt(6)
    p_col.add_run("Mỗi dòng phát hiện trùng lặp cung cấp bằng chứng pháp lý rõ ràng:")

    col_table = doc.add_table(rows=6, cols=2)
    col_table.alignment = WD_TABLE_ALIGNMENT.CENTER
    for i, title in enumerate(["Trường thông tin", "Ý nghĩa chi tiết"]):
        cell = col_table.cell(0, i)
        cell.width = col_widths[i]
        set_cell_background(cell, "0B2C4D")
        set_cell_margins(cell, top=120, bottom=120, left=160, right=160)
        p = cell.paragraphs[0]; pr = p.add_run(title)
        pr.font.name = "Segoe UI"; pr.font.bold = True; pr.font.size = Pt(9.5); pr.font.color.rgb = RGBColor(255, 255, 255)

    res_cols = [
        ("Video Gốc Trùng Khớp", "Tên video trong kho dữ liệu của công ty bị đối tượng sao chép."),
        ("Khoảng Target vs Khoảng Gốc", "Mốc thời gian chính xác đoạn cắt vi phạm (Ví dụ: Target từ 00:03-00:22 bị sao chép từ Gốc tại 00:08-00:27)."),
        ("Thời Lượng Trùng", "Tổng số giây video bị sao chép (Ví dụ: 17.0s, 60.5s,...)."),
        ("Độ Trùng (%)", "Tỷ lệ tương đồng do AI chấm điểm (Thường > 85% cho các đoạn cắt trực tiếp)."),
        ("Dạng Nhận Diện", "Phân loại hành vi: 'Hình ảnh & Âm thanh' (toàn diện), 'Chỉ Hình ảnh' (đã tắt tiếng/thay nhạc), 'Chỉ Âm thanh' (giữ tiếng nhưng thay hình).")
    ]

    for row_idx, (k, v) in enumerate(res_cols, start=1):
        bg = "FFFFFF" if row_idx % 2 != 0 else "F7FAFC"
        cell_k = col_table.cell(row_idx, 0); cell_v = col_table.cell(row_idx, 1)
        cell_k.width = col_widths[0]; cell_v.width = col_widths[1]
        for c in (cell_k, cell_v):
            set_cell_background(c, bg)
            set_cell_margins(c, top=80, bottom=80, left=140, right=140)
            set_cell_border(c, bottom={"val": "single", "sz": "4", "color": "E2E8F0"})
        
        pk = cell_k.paragraphs[0]; rk = pk.add_run(k)
        rk.font.name = "Segoe UI"; rk.font.bold = True; rk.font.size = Pt(9.5); rk.font.color.rgb = COLOR_PRIMARY
        
        pv = cell_v.paragraphs[0]; rv = pv.add_run(v)
        rv.font.name = "Segoe UI"; rv.font.size = Pt(9); rv.font.color.rgb = COLOR_DARK

    doc.add_paragraph().paragraph_format.space_before = Pt(8)

    # 5. KẾT LUẬN & THÔNG TIN HỖ TRỢ
    h5 = doc.add_paragraph()
    h5.paragraph_format.space_before = Pt(14); h5.paragraph_format.space_after = Pt(6)
    r = h5.add_run("5. KHUYẾN NGHỊ VẬN HÀNH & HỖ TRỢ KỸ THUẬT")
    r.font.name = "Segoe UI"; r.font.bold = True; r.font.size = Pt(13); r.font.color.rgb = COLOR_PRIMARY

    p_end = doc.add_paragraph()
    p_end.paragraph_format.line_spacing = 1.15
    p_end.add_run(
        "• Khuyến nghị: Ban vận hành nên chủ động lưu toàn bộ các tệp video sản phẩm gốc vào thư mục Data/ ngay khi phát hành để hệ thống tự động băm nén dấu vân tay sẵn sàng.\n"
        "• Khi phát hiện kênh đối thủ hoặc trang mạng xã hội đăng tải nội dung nghi ngờ, nhân viên chỉ cần tải video đó về, thả vào Target/ và bấm đối soát để có báo cáo bằng chứng trong 10 giây.\n"
        "• Đầu mối kỹ thuật: Bộ phận AI & Phần mềm luôn thường trực hỗ trợ điều chỉnh độ nhạy hoặc mở rộng quy mô kho dữ liệu lên hàng chục nghìn giờ video khi công ty có nhu cầu."
    )

    doc.save(str(output_path))
    print(f"[OK] Đã tạo thành công tài liệu Word: {output_path}")

if __name__ == "__main__":
    out_file = Path(r"c:\Projects\VideoDetection\HUONG_DAN_SU_DUNG_VIDEODETECTION.docx")
    build_docx(out_file)
