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

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

def set_cell_margins(cell, top=100, bottom=100, left=150, right=150):
    tcPr = cell._tc.get_or_add_tcPr()
    tcMar = OxmlElement('w:tcMar')
    for m, val in [('top', top), ('bottom', bottom), ('left', left), ('right', right)]:
        node = OxmlElement(f'w:{m}')
        node.set(qn('w:w'), str(val))
        node.set(qn('w:type'), 'dxa')
        tcMar.append(node)
    tcPr.append(tcMar)

def set_table_borders(table, color="CCCCCC", sz="4", val="single"):
    tblPr = table._tbl.tblPr
    borders = parse_xml(f'''
        <w:tblBorders {nsdecls("w")}>
            <w:top w:val="{val}" w:sz="{sz}" w:space="0" w:color="{color}"/>
            <w:bottom w:val="{val}" w:sz="{sz}" w:space="0" w:color="{color}"/>
            <w:left w:val="{val}" w:sz="{sz}" w:space="0" w:color="{color}"/>
            <w:right w:val="{val}" w:sz="{sz}" w:space="0" w:color="{color}"/>
            <w:insideH w:val="{val}" w:sz="{sz}" w:space="0" w:color="{color}"/>
            <w:insideV w:val="{val}" w:sz="{sz}" w:space="0" w:color="{color}"/>
        </w:tblBorders>
    ''')
    tblPr.append(borders)

def add_paragraph_with_runs(doc, text, style='Normal', space_before=0, space_after=6, line_spacing=1.15, align=WD_ALIGN_PARAGRAPH.LEFT, is_blockquote=False):
    p = doc.add_paragraph(style=style)
    p.alignment = align
    p.paragraph_format.space_before = Pt(space_before)
    p.paragraph_format.space_after = Pt(space_after)
    p.paragraph_format.line_spacing = line_spacing
    
    if is_blockquote:
        p.paragraph_format.left_indent = Inches(0.5)
        
    # Parse bold text **word**
    parts = re.split(r'(\*\*.*?\*\*)', text)
    for part in parts:
        if part.startswith('**') and part.endswith('**'):
            clean_part = part[2:-2]
            run = p.add_run(clean_part)
            run.bold = True
            run.font.name = 'Times New Roman'
            run.font.size = Pt(11)
            if is_blockquote:
                run.font.italic = True
                run.font.color.rgb = RGBColor(80, 80, 80)
        else:
            # Handle standard links [text](url) -> just keep the text
            clean_text = re.sub(r'\[(.*?)\]\(.*?\)', r'\1', part)
            # Remove raw markdown bold tags if any remaining
            clean_text = clean_text.replace('**', '')
            if clean_text:
                run = p.add_run(clean_text)
                run.font.name = 'Times New Roman'
                run.font.size = Pt(11)
                if is_blockquote:
                    run.font.italic = True
                    run.font.color.rgb = RGBColor(80, 80, 80)
    return p

def convert_md_to_docx(md_path, docx_path, doc_title_text):
    doc = Document()
    
    # Page setup
    section = doc.sections[0]
    section.top_margin = Inches(1)
    section.bottom_margin = Inches(1)
    section.left_margin = Inches(1)
    section.right_margin = Inches(1)

    # 1. Company Header
    p = doc.add_paragraph()
    p.alignment = WD_ALIGN_PARAGRAPH.CENTER
    run = p.add_run("CÔNG TY TNHH SX-TM HOÁ KEO BÌNH THẠNH (BT CHEM)")
    run.font.name = 'Times New Roman'
    run.font.size = Pt(12)
    run.bold = True
    
    p = doc.add_paragraph()
    p.alignment = WD_ALIGN_PARAGRAPH.CENTER
    p.paragraph_format.space_after = Pt(18)
    run = p.add_run("PHÒNG KINH DOANH / R&D\n— — —")
    run.font.name = 'Times New Roman'
    run.font.size = Pt(11)
    run.bold = True

    # 2. Document Title
    p = doc.add_paragraph()
    p.alignment = WD_ALIGN_PARAGRAPH.CENTER
    p.paragraph_format.space_before = Pt(12)
    p.paragraph_format.space_after = Pt(18)
    run = p.add_run(doc_title_text.upper())
    run.font.name = 'Times New Roman'
    run.font.size = Pt(16)
    run.bold = True
    run.font.color.rgb = RGBColor(0, 51, 102)

    with open(md_path, 'r', encoding='utf-8') as f:
        lines = f.readlines()

    in_table = False
    table_rows = []
    
    for line in lines:
        line_str = line.strip()
        
        # Skip empty lines or divider lines if not in table
        if not line_str and not in_table:
            continue
            
        # Parse table row
        if line_str.startswith('|') and line_str.endswith('|'):
            in_table = True
            # Skip separator row like |:---|---:|
            if re.match(r'^\|[\s:-|]*\|$', line_str):
                continue
            cells = [c.strip() for c in line_str.split('|')[1:-1]]
            table_rows.append(cells)
            continue
        else:
            # If we were in a table and it just ended, process the table
            if in_table:
                if table_rows:
                    cols_count = len(table_rows[0])
                    table = doc.add_table(rows=len(table_rows), cols=cols_count)
                    table.alignment = WD_TABLE_ALIGNMENT.CENTER
                    set_table_borders(table)
                    
                    for r_idx, row_data in enumerate(table_rows):
                        row = table.rows[r_idx]
                        is_header = (r_idx == 0)
                        
                        # Apply row height or padding
                        for c_idx, cell_text in enumerate(row_data):
                            # Ensure we don't index out of bounds
                            if c_idx >= len(row.cells):
                                continue
                            cell = row.cells[c_idx]
                            p_cell = cell.paragraphs[0]
                            p_cell.paragraph_format.space_after = Pt(4)
                            
                            # Replace <br> with newlines
                            clean_cell_text = cell_text.replace('<br>', '\n')
                            clean_cell_text = re.sub(r'\[(.*?)\]\(.*?\)', r'\1', clean_cell_text) # strip links
                            clean_cell_text = clean_cell_text.replace('**', '')
                            
                            run_c = p_cell.add_run(clean_cell_text)
                            run_c.font.name = 'Times New Roman'
                            run_c.font.size = Pt(9.5 if not is_header else 10)
                            
                            if is_header:
                                run_c.bold = True
                                set_cell_background(cell, "D9E1F2") # soft blue for headers
                            elif c_idx == 0:
                                # First column bold for key-value tables
                                run_c.bold = True
                                set_cell_background(cell, "F2F2F2") # soft grey
                                
                            set_cell_margins(cell, top=60, bottom=60, left=100, right=100)
                
                in_table = False
                table_rows = []
                doc.add_paragraph() # Add space after table

        # Parse Headings
        if line_str.startswith('# '):
            # Skip Heading 1 if it is the title since we added a styled title
            title_candidate = line_str[2:]
            if title_candidate.lower() in doc_title_text.lower() or "tổng hợp khách hàng" in title_candidate.lower() or "lọc danh sách" in title_candidate.lower():
                continue
            h = doc.add_paragraph()
            h.paragraph_format.space_before = Pt(18)
            h.paragraph_format.space_after = Pt(8)
            run = h.add_run(line_str[2:])
            run.font.name = 'Times New Roman'
            run.font.size = Pt(14)
            run.bold = True
            run.font.color.rgb = RGBColor(0, 51, 102)
        elif line_str.startswith('## '):
            h = doc.add_paragraph()
            h.paragraph_format.space_before = Pt(14)
            h.paragraph_format.space_after = Pt(6)
            run = h.add_run(line_str[3:])
            run.font.name = 'Times New Roman'
            run.font.size = Pt(13)
            run.bold = True
            run.font.color.rgb = RGBColor(0, 51, 102)
        elif line_str.startswith('### '):
            h = doc.add_paragraph()
            h.paragraph_format.space_before = Pt(10)
            h.paragraph_format.space_after = Pt(4)
            run = h.add_run(line_str[4:])
            run.font.name = 'Times New Roman'
            run.font.size = Pt(11.5)
            run.bold = True
            run.font.color.rgb = RGBColor(128, 0, 0) # maroon for subheadings
        elif line_str.startswith('#### '):
            h = doc.add_paragraph()
            h.paragraph_format.space_before = Pt(8)
            h.paragraph_format.space_after = Pt(4)
            run = h.add_run(line_str[5:])
            run.font.name = 'Times New Roman'
            run.font.size = Pt(11)
            run.bold = True
            run.font.color.rgb = RGBColor(80, 80, 80)
        # Parse Bullet Lists
        elif line_str.startswith('* ') or line_str.startswith('- '):
            content = line_str[2:]
            p = doc.add_paragraph(style='List Bullet')
            p.paragraph_format.space_after = Pt(3)
            # Parse bold text within bullet
            parts = re.split(r'(\*\*.*?\*\*)', content)
            for part in parts:
                if part.startswith('**') and part.endswith('**'):
                    run = p.add_run(part[2:-2])
                    run.bold = True
                else:
                    clean_text = re.sub(r'\[(.*?)\]\(.*?\)', r'\1', part)
                    clean_text = clean_text.replace('**', '')
                    run = p.add_run(clean_text)
                run.font.name = 'Times New Roman'
                run.font.size = Pt(11)
        # Parse Blockquotes
        elif line_str.startswith('> '):
            content = line_str[2:]
            add_paragraph_with_runs(doc, content, space_before=4, space_after=4, is_blockquote=True)
        # Parse Normal Paragraphs
        else:
            add_paragraph_with_runs(doc, line_str, space_before=0, space_after=6)
            
    doc.save(docx_path)
    print(f"Successfully converted {md_path} to {docx_path}")

if __name__ == '__main__':
    # Convert potential client report
    convert_md_to_docx(
        md_path="Bao_cao_khach_hang_tiem_nang.md",
        docx_path="Bao_cao_khach_hang_tiem_nang.docx",
        doc_title_text="Báo cáo tổng hợp khách hàng tiềm năng"
    )
    # Convert filtered buyers report
    convert_md_to_docx(
        md_path="Danh_sach_nha_mua_hang_loc.md",
        docx_path="Danh_sach_nha_mua_hang_loc.docx",
        doc_title_text="Báo cáo lọc danh sách nhà mua hàng quốc tế"
    )
