#!/usr/bin/env python3
"""
Gera planejamento_black_friday_2026.docx a partir do .md
"""

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

MD_PATH = "/opt/mia/workspace/clientes/francisco_borrello/planejamento_black_friday_2026.md"
DOCX_PATH = "/opt/mia/workspace/clientes/francisco_borrello/planejamento_black_friday_2026.docx"

# Paleta Borrello
DOURADO = RGBColor(0xE6, 0xB3, 0x24)
AZUL_NOITE = RGBColor(0x1A, 0x1A, 0x2E)
BRANCO = RGBColor(0xFF, 0xFF, 0xFF)
CINZA_CLARO = RGBColor(0xF5, 0xF5, 0xF5)
CINZA_TEXTO = RGBColor(0x33, 0x33, 0x33)


def set_cell_bg(cell, hex_color):
    tc = cell._tc
    tcPr = tc.get_or_add_tcPr()
    shd = OxmlElement('w:shd')
    shd.set(qn('w:val'), 'clear')
    shd.set(qn('w:color'), 'auto')
    shd.set(qn('w:fill'), hex_color)
    tcPr.append(shd)


def set_paragraph_bg(paragraph, hex_color):
    pPr = paragraph._p.get_or_add_pPr()
    shd = OxmlElement('w:shd')
    shd.set(qn('w:val'), 'clear')
    shd.set(qn('w:color'), 'auto')
    shd.set(qn('w:fill'), hex_color)
    pPr.append(shd)


def add_run(para, text, bold=False, italic=False, color=None, size=None):
    run = para.add_run(text)
    run.bold = bold
    run.italic = italic
    if color:
        run.font.color.rgb = color
    if size:
        run.font.size = Pt(size)
    return run


def parse_inline(para, text, base_size=11, base_color=None):
    """Processa **bold** e texto puro inline."""
    parts = re.split(r'(\*\*[^*]+\*\*)', text)
    for part in parts:
        if part.startswith('**') and part.endswith('**'):
            content = part[2:-2]
            add_run(para, content, bold=True, size=base_size, color=base_color or CINZA_TEXTO)
        else:
            add_run(para, part, size=base_size, color=base_color or CINZA_TEXTO)


def add_heading(doc, text, level):
    para = doc.add_paragraph()
    para.paragraph_format.space_before = Pt(16 if level == 1 else 10)
    para.paragraph_format.space_after = Pt(6)
    para.paragraph_format.keep_with_next = True

    if level == 1:
        set_paragraph_bg(para, '1A1A2E')
        para.paragraph_format.left_indent = Cm(0.5)
        run = para.add_run(text)
        run.bold = True
        run.font.size = Pt(18)
        run.font.color.rgb = DOURADO
    elif level == 2:
        run = para.add_run(text)
        run.bold = True
        run.font.size = Pt(14)
        run.font.color.rgb = AZUL_NOITE
        # linha dourada abaixo
        pPr = para._p.get_or_add_pPr()
        pBdr = OxmlElement('w:pBdr')
        bottom = OxmlElement('w:bottom')
        bottom.set(qn('w:val'), 'single')
        bottom.set(qn('w:sz'), '6')
        bottom.set(qn('w:space'), '1')
        bottom.set(qn('w:color'), 'E6B324')
        pBdr.append(bottom)
        pPr.append(pBdr)
    elif level == 3:
        set_paragraph_bg(para, 'E6B324')
        para.paragraph_format.left_indent = Cm(0.3)
        run = para.add_run(text)
        run.bold = True
        run.font.size = Pt(12)
        run.font.color.rgb = AZUL_NOITE
    elif level == 4:
        run = para.add_run(text)
        run.bold = True
        run.font.size = Pt(11)
        run.font.color.rgb = AZUL_NOITE
        run.font.italic = True
    return para


def add_table_from_lines(doc, header_line, rows):
    cols = [c.strip() for c in header_line.split('|') if c.strip()]
    n_cols = len(cols)
    if n_cols == 0:
        return

    table = doc.add_table(rows=1 + len(rows), cols=n_cols)
    table.style = 'Table Grid'
    table.alignment = WD_TABLE_ALIGNMENT.CENTER

    # Header
    for i, col in enumerate(cols):
        cell = table.cell(0, i)
        set_cell_bg(cell, '1A1A2E')
        p = cell.paragraphs[0]
        p.alignment = WD_ALIGN_PARAGRAPH.CENTER
        run = p.add_run(col)
        run.bold = True
        run.font.color.rgb = DOURADO
        run.font.size = Pt(10)

    for r_idx, row_line in enumerate(rows):
        cells_data = [c.strip() for c in row_line.split('|') if c.strip() != '']
        # pad
        while len(cells_data) < n_cols:
            cells_data.append('')
        for c_idx in range(n_cols):
            cell = table.cell(r_idx + 1, c_idx)
            if r_idx % 2 == 0:
                set_cell_bg(cell, 'F5F5F5')
            p = cell.paragraphs[0]
            p.alignment = WD_ALIGN_PARAGRAPH.LEFT
            text = cells_data[c_idx] if c_idx < len(cells_data) else ''
            parse_inline(p, text, base_size=10)

    doc.add_paragraph()


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

    table_buffer = []
    in_table = False

    def flush_table():
        nonlocal table_buffer, in_table
        if len(table_buffer) >= 3:
            header = table_buffer[0]
            # skip separator line (|---|)
            rows = [l for l in table_buffer[2:] if l.strip() and not re.match(r'\|[-| ]+\|', l)]
            add_table_from_lines(doc, header, rows)
        table_buffer = []
        in_table = False

    for line in lines:
        raw = line.rstrip('\n')

        # Detect table
        if raw.strip().startswith('|'):
            in_table = True
            table_buffer.append(raw.strip())
            continue
        else:
            if in_table:
                flush_table()

        stripped = raw.strip()

        if not stripped:
            doc.add_paragraph()
            continue

        # Headings
        h4 = re.match(r'^#### (.+)', stripped)
        h3 = re.match(r'^### (.+)', stripped)
        h2 = re.match(r'^## (.+)', stripped)
        h1 = re.match(r'^# (.+)', stripped)

        if h1:
            add_heading(doc, h1.group(1), 1)
            continue
        if h2:
            add_heading(doc, h2.group(1), 2)
            continue
        if h3:
            add_heading(doc, h3.group(1), 3)
            continue
        if h4:
            add_heading(doc, h4.group(1), 4)
            continue

        # Horizontal rule
        if stripped.startswith('---'):
            para = doc.add_paragraph()
            pPr = para._p.get_or_add_pPr()
            pBdr = OxmlElement('w:pBdr')
            bottom = OxmlElement('w:bottom')
            bottom.set(qn('w:val'), 'single')
            bottom.set(qn('w:sz'), '4')
            bottom.set(qn('w:space'), '1')
            bottom.set(qn('w:color'), 'E6B324')
            pBdr.append(bottom)
            pPr.append(pBdr)
            continue

        # Bullet (- or *)
        bullet_match = re.match(r'^[-*] (.+)', stripped)
        if bullet_match:
            para = doc.add_paragraph(style='List Bullet')
            para.paragraph_format.left_indent = Cm(0.8)
            para.paragraph_format.space_after = Pt(3)
            parse_inline(para, bullet_match.group(1), base_size=11)
            continue

        # Numbered list
        num_match = re.match(r'^\d+\. (.+)', stripped)
        if num_match:
            para = doc.add_paragraph(style='List Number')
            para.paragraph_format.left_indent = Cm(0.8)
            para.paragraph_format.space_after = Pt(3)
            parse_inline(para, num_match.group(1), base_size=11)
            continue

        # Regular paragraph
        para = doc.add_paragraph()
        para.paragraph_format.space_after = Pt(6)
        para.alignment = WD_ALIGN_PARAGRAPH.JUSTIFY
        parse_inline(para, stripped, base_size=11)

    if in_table:
        flush_table()


def build_cover(doc):
    """Página de capa"""
    # Espaço antes do título
    for _ in range(4):
        doc.add_paragraph()

    p = doc.add_paragraph()
    p.alignment = WD_ALIGN_PARAGRAPH.CENTER
    set_paragraph_bg(p, '1A1A2E')
    run = p.add_run('PLANEJAMENTO BLACK FRIDAY 2026')
    run.bold = True
    run.font.size = Pt(22)
    run.font.color.rgb = DOURADO

    p2 = doc.add_paragraph()
    p2.alignment = WD_ALIGN_PARAGRAPH.CENTER
    set_paragraph_bg(p2, '1A1A2E')
    run2 = p2.add_run('Francisco Borrello × Climb Digital')
    run2.font.size = Pt(14)
    run2.font.color.rgb = BRANCO

    doc.add_paragraph()

    meta = [
        ('Data de elaboração', '07/10/2026'),
        ('Black Friday', '28/11/2026 (sábado)'),
        ('Janela de vendas', '17/11 a 02/12/2026'),
        ('Semanas disponíveis', '7 semanas'),
        ('Elaborado por', 'Jonathan — Climb Digital'),
    ]

    table = doc.add_table(rows=len(meta), cols=2)
    table.alignment = WD_TABLE_ALIGNMENT.CENTER
    for i, (k, v) in enumerate(meta):
        c0 = table.cell(i, 0)
        c1 = table.cell(i, 1)
        set_cell_bg(c0, '1A1A2E')
        set_cell_bg(c1, '2A2A3E')
        p0 = c0.paragraphs[0]
        p1 = c1.paragraphs[0]
        r0 = p0.add_run(k)
        r0.bold = True
        r0.font.color.rgb = DOURADO
        r0.font.size = Pt(11)
        r1 = p1.add_run(v)
        r1.font.color.rgb = BRANCO
        r1.font.size = Pt(11)

    doc.add_page_break()


def main():
    doc = Document()

    # Margens
    for section in doc.sections:
        section.top_margin = Cm(2)
        section.bottom_margin = Cm(2)
        section.left_margin = Cm(2.5)
        section.right_margin = Cm(2.5)

    # Estilo base
    style = doc.styles['Normal']
    style.font.name = 'Calibri'
    style.font.size = Pt(11)
    style.font.color.rgb = CINZA_TEXTO

    build_cover(doc)
    process_md(doc, MD_PATH)

    doc.save(DOCX_PATH)
    print(f"Salvo em: {DOCX_PATH}")


if __name__ == '__main__':
    main()
