#!/usr/bin/env python3
"""
HTML to DOCX Converter for JvG Consultancy Contracts
Converteert HTML-contracten naar DOCX-formaat met JvG branding
"""

import os
import re
from pathlib import Path
from docx import Document
from docx.shared import Inches, Pt
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.enum.style import WD_STYLE_TYPE
from docx.oxml.ns import qn

# Importeer de HTML parser
from bs4 import BeautifulSoup

# JvG Branding Specificaties
JVG_PRIMARY_COLOR = "#003366"
JVG_TEXT_COLOR = "#1F2937"
JVG_BG_COLOR = "#FFFFFF"
JVG_BORDER_COLOR = "#E5E7EB"
JVG_FONT_NAME = "Calibri"
JVG_FOOTER_TEXT = "JvG Consultancy | Safety • Governance • Advisory | © 2026"
JVG_LOGO_PATH = "/root/projects/jg/assets/branding/jvg-logo-white-medium.png"

def clean_html_content(html_content):
    """Reinig HTML-content voor verwerking in DOCX"""
    # Verwijder HTML-tags en behoud tekststructuur
    soup = BeautifulSoup(html_content, 'html.parser')
    
    # Behoud specifieke elementen voor structuur
    content = ""
    
    # Verwerk header
    header = soup.find('div', class_='header')
    if header:
        title_div = header.find('div', class_='title')
        if title_div:
            content += f"{title_div.get_text(strip=True)}\n\n"
        
        subtitle_div = header.find('div', class_='subtitle')
        if subtitle_div:
            content += f"{subtitle_div.get_text(strip=True)}\n\n"
        
        project_info = header.find('div', class_='project-info')
        if project_info:
            info_rows = project_info.find_all('div', class_='info-row')
            for row in info_rows:
                content += f"{row.get_text(strip=True)}\n"
            content += "\n"
    
    # Verwerk hoofdcontent
    content_div = soup.find('div', class_='content')
    if content_div:
        # Verwerk H1
        for h1 in content_div.find_all('h1'):
            content += f"\n{h1.get_text(strip=True)}\n\n"
        
        # Verwerk H2 (Artikelen)
        for h2 in content_div.find_all('h2'):
            content += f"\n{h2.get_text(strip=True)}\n\n"
            
            # Verwerk artikelen binnen secties
            article = h2.find_next_sibling('div', class_='article')
            if article:
                article_number = article.find('span', class_='article-number')
                if article_number:
                    content += f"{article_number.get_text(strip=True)}"
                
                # Verhaal de rest van de inhoud
                for element in article.contents:
                    if element.name == 'ul':
                        for li in element.find_all('li'):
                            content += f"\n  {li.get_text(strip=True)}"
                    elif element.name == 'p':
                        content += f"\n{element.get_text(strip=True)}"
                    elif element.name and element.name != 'span':
                        content += f"\n{element.get_text(strip=True)}"
                
                content += "\n\n"
        
        # Verwerking signature block
        signature_div = content_div.find('div', class_='signature')
        if signature_div:
            content += "\n\n"
            for block in signature_div.find_all('div', class_='signature-block'):
                content += f"{block.get_text(strip=True)}\n\n"
        
        # Bronverwijzingen
        sources_div = content_div.find('div', class_='sources')
        if sources_div:
            content += f"\n{sources_div.get_text(strip=True)}\n\n"
        
        # Verificatie
        verify_div = content_div.find('div', class_='verify')
        if verify_div:
            content += f"\n{verify_div.get_text(strip=True)}\n\n"
    
    # Footer wordt apart verwerkt
    return content.strip()

def setup_document_styles(doc):
    """Stel JvG stijlen in voor het document"""
    # Stel hoofdlettertype in
    styles = doc.styles
    
    # Kop 1 stijl
    try:
        h1_style = styles.add_style('Hoofdtitel', WD_STYLE_TYPE.PARAGRAPH)
        h1_style.base_style = styles['Heading 1']
        h1_style.font.name = JVG_FONT_NAME
        h1_font = h1_style.font
        h1_font.size = Pt(16)
        h1_font.bold = True
        h1_font.color.rgb = qn(JVG_PRIMARY_COLOR)
        h1_style.paragraph_format.space_after = Pt(15)
    except:
        pass
    
    # Kop 2 stijl (Artikelen)
    try:
        h2_style = styles.add_style('Sectietitel', WD_STYLE_TYPE.PARAGRAPH)
        h2_style.base_style = styles['Heading 2']
        h2_style.font.name = JVG_FONT_NAME
        h2_font = h2_style.font
        h2_font.size = Pt(14)
        h2_font.bold = True
        h2_font.color.rgb = qn(JVG_PRIMARY_COLOR)
        h2_style.paragraph_format.space_after = Pt(10)
    except:
        pass
    
    # Body tekst stijl
    try:
        body_style = styles.add_style('BodyTekst', WD_STYLE_TYPE.PARAGRAPH)
        body_style.font.name = JVG_FONT_NAME
        body_font = body_style.font
        body_font.size = Pt(11)
        body_font.color.rgb = qn(JVG_TEXT_COLOR)
        body_style.paragraph_format.space_after = Pt(10)
        body_style.paragraph_format.line_spacing = 1.5
    except:
        pass

def add_header_section(doc, html_content, company_name):
    """Voeg de header sectie toe met projectinfo"""
    # Haal de header-info uit de HTML
    soup = BeautifulSoup(html_content, 'html.parser')
    header = soup.find('div', class_='header')
    
    if header:
        # Voeg een sectie toe voor de header
        section = doc.add_paragraph()
        section.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER
        section.paragraph_format.space_after = Pt(20)
        
        # Logo wordt in de footer verwerkt
        # Titel
        title = doc.add_paragraph()
        title.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER
        title_run = title.add_run("OVEREENKOMST VAN OPDRACHT")
        title_run.font.name = JVG_FONT_NAME
        title_run.font.size = Pt(14)
        title_run.font.bold = True
        title_run.font.color.rgb = qn(JVG_PRIMARY_COLOR)
        title.paragraph_format.space_after = Pt(10)
        
        # Subtitle
        subtitle = doc.add_paragraph()
        subtitle.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER
        subtitle_run = subtitle.add_run(f"tussen {company_name} en [BEDRIJFSNAAM]")
        subtitle_run.font.name = JVG_FONT_NAME
        subtitle_run.font.size = Pt(12)
        subtitle_run.font.color.rgb = qn(JVG_TEXT_COLOR)
        subtitle.paragraph_format.space_after = Pt(20)
        
        # Project info
        info_table = doc.add_table(rows=2, cols=3)
        info_table.style = 'Light Grid Accent 1'
        
        # Vul de tabel met projectinfo
        cells = info_table.rows[0].cells
        cells[0].text = "Project: 2026-hseq-contract-opdracht"
        cells[1].text = "Type: Overeenkomst van Opdracht"
        cells[2].text = "Auteur: JvG Consultancy"
        
        cells = info_table.rows[1].cells
        cells[0].text = "Versie: v1.0"
        cells[1].text = "Datum: 28 mei 2026"
        cells[2].text = "Status: Concept"
        
        # Pas kleur toe op tabelrij
        for row in info_table.rows:
            for cell in row.cells:
                cell.paragraphs[0].runs[0].font.color.rgb = qn(JVG_TEXT_COLOR)

def add_footer(doc, doc_type):
    """Voeg footer met branding en logo toe"""
    # Voeg een sectie toe voor de footer
    section = doc.add_paragraph()
    section.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER
    section.paragraph_format.space_before = Pt(30)
    
    # Footer tekst
    footer_text = doc.add_paragraph()
    footer_run = footer_text.add_run(JVG_FOOTER_TEXT)
    footer_run.font.name = JVG_FONT_NAME
    footer_run.font.size = Pt(10)
    footer_run.font.color.rgb = qn(JVG_PRIMARY_COLOR)

def convert_html_to_docx(html_path, output_path, company_name):
    """Converteer HTML naar DOCX met JvG branding"""
    # Lees HTML-bestand
    with open(html_path, 'r', encoding='utf-8') as f:
        html_content = f.read()
    
    # Maak nieuw DOCX document
    doc = Document()
    
    # Stel JvG stijlen in
    setup_document_styles(doc)
    
    # Voeg header toe
    add_header_section(doc, html_content, company_name)
    
    # Reinig en verwerk HTML-content
    clean_content = clean_html_content(html_content)
    
    # Verwerk de content in het document
    lines = clean_content.split('\n')
    current_section = None
    
    for line in lines:
        line = line.strip()
        if not line:
            continue
        
        # Detecteer sectiekoppen (H1)
        if line == "OVEREENKOMST VAN OPDRACHT":
            p = doc.add_paragraph()
            p.paragraph_format.space_before = Pt(20)
            run = p.add_run(line)
            run.font.name = JVG_FONT_NAME
            run.font.size = Pt(16)
            run.font.bold = True
            run.font.color.rgb = qn(JVG_PRIMARY_COLOR)
            current_section = None
            continue
        
        # Detecteer artikelkoppen (H2)
        if line.startswith("Artikel"):
            p = doc.add_paragraph()
            p.paragraph_format.space_before = Pt(15)
            p.paragraph_format.space_after = Pt(10)
            run = p.add_run(line)
            run.font.name = JVG_FONT_NAME
            run.font.size = Pt(14)
            run.font.bold = True
            run.font.color.rgb = qn(JVG_PRIMARY_COLOR)
            current_section = line
            continue
        
        # Detecteer sub-artikel nummers
        if re.match(r'\d+\.\d+\.', line):
            p = doc.add_paragraph()
            p.paragraph_format.left_indent = Inches(0.5)
            p.paragraph_format.space_after = Pt(8)
            run = p.add_run(line)
            run.font.name = JVG_FONT_NAME
            run.font.size = Pt(11)
            run.font.bold = True
            run.font.color.rgb = qn(JVG_TEXT_COLOR)
            continue
        
        # Verwerk lijsten
        if line.startswith("  - ") or line.startswith("  * "):
            p = doc.add_paragraph()
            p.paragraph_format.left_indent = Inches(0.5)
            p.paragraph_format.space_after = Pt(6)
            run = p.add_run(line[3:])  # Verwijder de prefix "  - " of "  * "
            run.font.name = JVG_FONT_NAME
            run.font.size = Pt(11)
            run.font.color.rgb = qn(JVG_TEXT_COLOR)
            continue
        
        # Verwerk normale paragrafen
        if current_section and not line.startswith("Artikel"):
            p = doc.add_paragraph()
            p.paragraph_format.left_indent = Inches(0.5)
            p.paragraph_format.space_after = Pt(8)
            run = p.add_run(line)
            run.font.name = JVG_FONT_NAME
            run.font.size = Pt(11)
            run.font.color.rgb = qn(JVG_TEXT_COLOR)
            continue
        else:
            p = doc.add_paragraph()
            p.paragraph_format.space_after = Pt(10)
            run = p.add_run(line)
            run.font.name = JVG_FONT_NAME
            run.font.size = Pt(11)
            run.font.color.rgb = qn(JVG_TEXT_COLOR)
    
    # Voeg footer toe
    add_footer(doc, company_name)
    
    # Sla het document op
    doc.save(output_path)
    print(f"Successvol geconverteerd: {output_path}")

def main():
    """Hoofdfunctie voor het converteren van HTML naar DOCX"""
    
    # Definieer bronbestanden en doelformaten
    source_files = [
        {
            'input': '/root/projects/jg/2026-hseq-contract-opdracht/deliverables/overeenkomst_opdracht_phoenix_metals_v1.0.html',
            'output': '/root/projects/jg/2026-hseq-contract-opdracht/deliverables/Overeenkomst_van_Opdracht_Phoenix_Metals_BV_v1.0.docx',
            'company': 'Phoenix Metals B.V.'
        },
        {
            'input': '/root/projects/jg/2026-hseq-contract-opdracht/deliverables/overeenkomst_opdracht_club_engineers_v1.0.html',
            'output': '/root/projects/jg/2026-hseq-contract-opdracht/deliverables/Overeenkomst_van_Opdracht_Club_of_Engineers_BV_v1.0.docx',
            'company': 'Club of Engineers B.V.'
        }
    ]
    
    # Controleer of de bronbestanden bestaan
    for source_file in source_files:
        if not os.path.exists(source_file['input']):
            print(f"Fout: Bronbestand niet gevonden: {source_file['input']}")
            return False
    
    # Maak de output directory aan als deze niet bestaat
    os.makedirs('/root/projects/jg/2026-hseq-contract-opdracht/deliverables', exist_ok=True)
    
    # Converteer elk bestand
    for source_file in source_files:
        try:
            print(f"Converteer {source_file['input']} naar {source_file['output']}")
            convert_html_to_docx(source_file['input'], source_file['output'], source_file['company'])
            print(f"Succes: {source_file['output']} aangemaakt")
        except Exception as e:
            print(f"Fout bij converteren van {source_file['input']}: {str(e)}")
            return False
    
    return True

if __name__ == "__main__":
    success = main()
    if success:
        print("\nConversie voltooid! Alle HTML-contracten zijn succesvol geconverteerd naar DOCX-formaat met JvG branding.")
    else:
        print("\nConversie mislukt. Controleer de foutmeldingen.")