# -*- coding: utf-8 -*-
"""
generate_grading_docx.py
國文作文批改助手 - Word (.docx) 自動生成核心腳本
支援多位學生批改資料、成績總表、分段修改對照表、進階鷹架、完整示範作文與全班教學診斷。
"""

import docx
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 parse_xml
from docx.oxml.ns import nsdecls
import os
import shutil

def set_cell_background(cell, fill_hex):
    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=120, bottom=120, left=150, right=150):
    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_run_font(run, font_name="微軟正黑體", size_pt=10.5, bold=False, color_rgb=(30, 41, 59), italic=False):
    run.font.name = font_name
    run._r.get_or_add_rPr().append(parse_xml(f'<w:rFonts {nsdecls("w")} w:eastAsia="{font_name}"/>'))
    run.font.size = Pt(size_pt)
    run.bold = bold
    run.italic = italic
    run.font.color.rgb = RGBColor(*color_rgb)

def add_heading_styled(doc, text, level=1):
    p = doc.add_paragraph()
    p.paragraph_format.keep_with_next = True
    if level == 1:
        p.paragraph_format.space_before = Pt(22)
        p.paragraph_format.space_after = Pt(8)
        run = p.add_run(text)
        set_run_font(run, "微軟正黑體", 15, bold=True, color_rgb=(30, 58, 138))
        pBdr = parse_xml(f'<w:pBdr {nsdecls("w")}><w:bottom w:val="single" w:sz="14" w:space="4" w:color="1E3A8A"/></w:pBdr>')
        p._p.get_or_add_pPr().append(pBdr)
    elif level == 2:
        p.paragraph_format.space_before = Pt(14)
        p.paragraph_format.space_after = Pt(6)
        run = p.add_run(text)
        set_run_font(run, "微軟正黑體", 12.5, bold=True, color_rgb=(2, 132, 199))
    elif level == 3:
        p.paragraph_format.space_before = Pt(10)
        p.paragraph_format.space_after = Pt(4)
        run = p.add_run(text)
        set_run_font(run, "微軟正黑體", 11, bold=True, color_rgb=(15, 23, 42))
    return p

def build_essay_grading_docx(title, subtitle, meta_info, summary_table_data, students_data, general_diagnosis, output_paths):
    """
    建立完整的 Word 批改報告並儲存至多個目標路徑
    """
    doc = Document()
    
    # 設置頁邊距 (1 inch / 2.54 cm)
    for section in doc.sections:
        section.top_margin = Inches(1.0)
        section.bottom_margin = Inches(1.0)
        section.left_margin = Inches(1.0)
        section.right_margin = Inches(1.0)
        section.page_width = Inches(8.27)
        section.page_height = Inches(11.69)

    # 封面抬頭
    p_title = doc.add_paragraph()
    p_title.paragraph_format.space_before = Pt(10)
    p_title.paragraph_format.space_after = Pt(4)
    p_title.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER
    r_title = p_title.add_run(title)
    set_run_font(r_title, "微軟正黑體", 22, bold=True, color_rgb=(30, 58, 138))
    
    p_sub = doc.add_paragraph()
    p_sub.paragraph_format.space_before = Pt(0)
    p_sub.paragraph_format.space_after = Pt(16)
    p_sub.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER
    r_sub = p_sub.add_run(subtitle)
    set_run_font(r_sub, "微軟正黑體", 13, bold=False, color_rgb=(71, 85, 105))
    
    p_meta = doc.add_paragraph()
    p_meta.paragraph_format.space_before = Pt(0)
    p_meta.paragraph_format.space_after = Pt(20)
    p_meta.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER
    r_meta = p_meta.add_run(meta_info)
    set_run_font(r_meta, "微軟正黑體", 9.5, italic=True, color_rgb=(100, 116, 139))
    
    # 成績總覽表
    if summary_table_data:
        add_heading_styled(doc, "📋 寫作測驗成績總覽與評級統計", level=2)
        tbl_sum = doc.add_table(rows=len(summary_table_data), cols=len(summary_table_data[0]))
        tbl_sum.alignment = WD_TABLE_ALIGNMENT.CENTER
        tbl_sum.autofit = False
        
        col_widths = [Inches(0.6), Inches(0.9), Inches(1.2), Inches(0.9), Inches(0.9), Inches(2.2)]
        for r_idx, row in enumerate(summary_table_data):
            for c_idx, val in enumerate(row):
                cell = tbl_sum.cell(r_idx, c_idx)
                if c_idx < len(col_widths):
                    cell.width = col_widths[c_idx]
                cell.vertical_alignment = WD_ALIGN_VERTICAL.CENTER
                set_cell_margins(cell, top=100, bottom=100, left=100, right=100)
                
                p = cell.paragraphs[0]
                p.paragraph_format.space_before = Pt(2)
                p.paragraph_format.space_after = Pt(2)
                
                if r_idx == 0:
                    set_cell_background(cell, "1E3A8A")
                    p.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER
                    r = p.add_run(val)
                    set_run_font(r, "微軟正黑體", 9.5, bold=True, color_rgb=(255, 255, 255))
                else:
                    bg = "F8FAFC" if r_idx % 2 == 1 else "FFFFFF"
                    if "6" in val and c_idx == 3:
                        bg = "DCFCE7"
                    set_cell_background(cell, bg)
                    p.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER if c_idx in [0, 3, 4] else WD_ALIGN_PARAGRAPH.LEFT
                    r = p.add_run(val)
                    bold_flag = True if (c_idx in [1, 3] or (c_idx == 3 and "6" in val)) else False
                    color = (22, 101, 52) if (c_idx == 3 and "6" in val) else (30, 41, 59)
                    set_run_font(r, "微軟正黑體", 9.5, bold=bold_flag, color_rgb=color)
        doc.add_paragraph()

    # 學生個別報告
    for stu in students_data:
        doc.add_page_break()
        
        # 標題
        p_stu = doc.add_paragraph()
        p_stu.paragraph_format.space_before = Pt(14)
        p_stu.paragraph_format.space_after = Pt(4)
        run_name = p_stu.add_run(f"🧑‍🎓 座號 {stu['seat']} {stu['name']} 同學 寫作評估報告")
        set_run_font(run_name, "微軟正黑體", 16, bold=True, color_rgb=(30, 58, 138))
        
        # 基本資訊卡片
        tbl_info = doc.add_table(rows=1, cols=4)
        tbl_info.alignment = WD_TABLE_ALIGNMENT.CENTER
        tbl_info.autofit = False
        tbl_info.columns[0].width = Inches(1.8)
        tbl_info.columns[1].width = Inches(1.6)
        tbl_info.columns[2].width = Inches(1.5)
        tbl_info.columns[3].width = Inches(1.6)
        
        info_items = [
            ("作文題目", stu.get('topic', '作文題目')),
            ("班級座號", f"{stu['grade']} / {stu['seat']} 號"),
            ("評定級分", stu['score_level']),
            ("百分制換算", stu['score_num'])
        ]
        for i, (k, v) in enumerate(info_items):
            cell = tbl_info.cell(0, i)
            set_cell_background(cell, "F1F5F9")
            set_cell_margins(cell, top=80, bottom=80, left=100, right=100)
            p = cell.paragraphs[0]
            p.paragraph_format.space_before = Pt(0)
            p.paragraph_format.space_after = Pt(0)
            p.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER
            r_k = p.add_run(f"{k}\n")
            set_run_font(r_k, "微軟正黑體", 8.5, color_rgb=(100, 116, 139))
            r_v = p.add_run(v)
            color = (22, 101, 52) if "6" in v else (30, 58, 138)
            set_run_font(r_v, "微軟正黑體", 10.5, bold=True, color_rgb=color)
        doc.add_paragraph()

        # 分段修改對照表
        add_heading_styled(doc, "【📊 分段修改對照表】", level=2)
        tbl_comp = doc.add_table(rows=len(stu['comparisons']) + 1, cols=3)
        tbl_comp.alignment = WD_TABLE_ALIGNMENT.CENTER
        tbl_comp.autofit = False
        tbl_comp.columns[0].width = Inches(2.1)
        tbl_comp.columns[1].width = Inches(2.3)
        tbl_comp.columns[2].width = Inches(2.1)
        
        for c_idx, h in enumerate(["你的原文", "修改後原文", "修改重點說明"]):
            cell = tbl_comp.cell(0, c_idx)
            set_cell_background(cell, "E2E8F0")
            set_cell_margins(cell, top=100, bottom=100, left=100, right=100)
            p = cell.paragraphs[0]
            p.paragraph_format.space_before = Pt(2)
            p.paragraph_format.space_after = Pt(2)
            p.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER
            r = p.add_run(h)
            set_run_font(r, "微軟正黑體", 9.5, bold=True, color_rgb=(30, 41, 59))
            
        for r_idx, comp in enumerate(stu['comparisons']):
            row_cells = [tbl_comp.cell(r_idx + 1, 0), tbl_comp.cell(r_idx + 1, 1), tbl_comp.cell(r_idx + 1, 2)]
            row_texts = [comp['orig'], comp['mod'], comp['exp']]
            bg_colors = ["FEF2F2", "F0FDF4", "F8FAFC"]
            text_colors = [(185, 28, 28), (22, 101, 52), (51, 65, 85)]
            for c_idx in range(3):
                cell = row_cells[c_idx]
                set_cell_background(cell, bg_colors[c_idx])
                set_cell_margins(cell, top=100, bottom=100, left=100, right=100)
                p = cell.paragraphs[0]
                p.paragraph_format.space_before = Pt(2)
                p.paragraph_format.space_after = Pt(2)
                p.paragraph_format.line_spacing = 1.25
                r = p.add_run(row_texts[c_idx])
                set_run_font(r, "微軟正黑體", 9.0, color_rgb=text_colors[c_idx])
        doc.add_paragraph()

        # 寫作鷹架 (若有)
        if stu.get('scaffold'):
            add_heading_styled(doc, "【🏗️ 寫作進階鷹架】", level=2)
            scaffold_text = (
                f"📌 【細節擴寫引導】\n{stu['scaffold']['detail_expansion']}\n\n"
                f"🎨 【五感描摹建議】\n{stu['scaffold']['sensory_guide']}\n\n"
                f"💡 【邏輯/情感深度延伸】\n{stu['scaffold']['logic_emotional_extension']}"
            )
            tbl_scaff = doc.add_table(rows=1, cols=1)
            tbl_scaff.alignment = WD_TABLE_ALIGNMENT.CENTER
            tbl_scaff.autofit = False
            tbl_scaff.columns[0].width = Inches(6.5)
            c = tbl_scaff.cell(0, 0)
            set_cell_background(c, "FFFBEB")
            set_cell_margins(c, top=120, bottom=120, left=150, right=150)
            borders = parse_xml(f'''
                <w:tcBorders {nsdecls("w")}>
                    <w:top w:val="none"/><w:left w:val="single" w:sz="24" w:space="0" w:color="F59E0B"/>
                    <w:bottom w:val="none"/><w:right w:val="none"/>
                </w:tcBorders>
            ''')
            c._tc.get_or_add_tcPr().append(borders)
            p_sc = c.paragraphs[0]
            p_sc.paragraph_format.space_before = Pt(2)
            p_sc.paragraph_format.space_after = Pt(4)
            p_sc.paragraph_format.line_spacing = 1.3
            r_sc = p_sc.add_run(scaffold_text)
            set_run_font(r_sc, "微軟正黑體", 9.5, color_rgb=(120, 53, 15))
            doc.add_paragraph()

        # 老師示範寫作 (完整版)
        add_heading_styled(doc, "【📝 老師示範寫作 (完整版)】", level=2)
        tbl_ex = doc.add_table(rows=1, cols=1)
        tbl_ex.alignment = WD_TABLE_ALIGNMENT.CENTER
        tbl_ex.autofit = False
        tbl_ex.columns[0].width = Inches(6.5)
        c_ex = tbl_ex.cell(0, 0)
        set_cell_background(c_ex, "FAFAF9")
        set_cell_margins(c_ex, top=140, bottom=140, left=180, right=160)
        borders = parse_xml(f'''
            <w:tcBorders {nsdecls("w")}>
                <w:top w:val="none"/><w:left w:val="single" w:sz="24" w:space="0" w:color="0284C7"/>
                <w:bottom w:val="none"/><w:right w:val="none"/>
            </w:tcBorders>
        ''')
        c_ex._tc.get_or_add_tcPr().append(borders)
        
        p_t = c_ex.paragraphs[0]
        p_t.paragraph_format.space_before = Pt(2)
        p_t.paragraph_format.space_after = Pt(8)
        p_t.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER
        r_t = p_t.add_run(stu['exemplar_title'])
        set_run_font(r_t, "微軟正黑體", 12, bold=True, color_rgb=(2, 132, 199))
        
        for para_text in stu['exemplar_paras']:
            p_p = c_ex.add_paragraph()
            p_p.paragraph_format.space_before = Pt(2)
            p_p.paragraph_format.space_after = Pt(6)
            p_p.paragraph_format.line_spacing = 1.35
            p_p.paragraph_format.first_line_indent = Inches(0.28)
            r_p = p_p.add_run(para_text)
            set_run_font(r_p, "微軟正黑體", 10.0, color_rgb=(51, 65, 85))
        doc.add_paragraph()

        # 國文老師的成長建議
        add_heading_styled(doc, "【💡 國文老師的成長建議】", level=2)
        for label, text in stu['advices']:
            p_adv = doc.add_paragraph()
            p_adv.paragraph_format.space_before = Pt(3)
            p_adv.paragraph_format.space_after = Pt(5)
            p_adv.paragraph_format.line_spacing = 1.3
            p_adv.paragraph_format.left_indent = Inches(0.2)
            r_lbl = p_adv.add_run(f"• {label} ")
            set_run_font(r_lbl, "微軟正黑體", 10.0, bold=True, color_rgb=(180, 83, 9))
            r_txt = p_adv.add_run(text)
            set_run_font(r_txt, "微軟正黑體", 10.0, color_rgb=(51, 65, 85))

    # 全班教學診斷
    if general_diagnosis:
        doc.add_page_break()
        add_heading_styled(doc, "🎯 國文老師的整體教學診斷與寫作指導方針", level=1)
        for title_diag, content_diag in general_diagnosis:
            add_heading_styled(doc, title_diag, level=2)
            for p_line in content_diag.split("\n"):
                p = doc.add_paragraph()
                p.paragraph_format.space_before = Pt(3)
                p.paragraph_format.space_after = Pt(4)
                p.paragraph_format.line_spacing = 1.3
                p.paragraph_format.first_line_indent = Inches(0.25)
                r = p.add_run(p_line.strip())
                set_run_font(r, "微軟正黑體", 10.5, color_rgb=(51, 65, 85))
                
    # 儲存檔案
    for path in output_paths:
        os.makedirs(os.path.dirname(path), exist_ok=True)
        doc.save(path)
        print(f"Report successfully saved to: {path}")

