#!/usr/bin/env python3
"""
DOCX Converter voor Phoenix Metals PGS 15 project
Converteert MD bestanden naar DOCX met JvG branding en opmaak
Volgens MASTER_STYLEGUIDE v1.2
"""

import os
import re
from docx import Document
from docx.shared import Inches, Pt
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.oxml.shared import OxmlElement, qn
from docx.shared import RGBColor
from datetime import datetime

class DocxConverter:
    def __init__(self):
        self.branding_logo_path = "/root/projects/jg/assets/branding/jvg-logo-white-medium.png"
        self.project_name = "Phoenix Metals"
        self.project_date = "27 april 2026"
        
    def create_document_header(self, doc, title, doc_type="Procedure"):
        """Create document header with JvG branding"""
        # Add logo to header
        section = doc.sections[0]
        header = section.header
        
        # Clear existing header content
        header.paragraphs.clear()
        
        # Add logo to right side of header
        if os.path.exists(self.branding_logo_path):
            run = header.paragraphs[0].add_run() if header.paragraphs else header.add_paragraph().add_run()
            run.add_picture(self.branding_logo_path, width=Inches(1.36), height=Inches(0.9))
        
        # Add document title to left side
        title_para = header.paragraphs[0] if header.paragraphs else header.add_paragraph()
        title_para.text = f"{doc_type} — {title}"
        title_para.style = 'Heading 1'
        title_para.alignment = WD_ALIGN_PARAGRAPH.LEFT
        
    def create_document_footer(self, doc, doc_name):
        """Create document footer with version info"""
        section = doc.sections[0]
        footer = section.footer
        
        # Clear existing footer content
        footer.paragraphs.clear()
        
        footer_para = footer.add_paragraph()
        footer_para.text = f"{self.project_name} | {doc_name}_v1.0 | {self.project_date}"
        footer_para.alignment = WD_ALIGN_PARAGRAPH.CENTER
        
    def convert_markdown_to_docx(self, md_file_path, output_docx_path, doc_type="Procedure"):
        """Convert markdown file to DOCX with proper formatting"""
        
        # Read markdown content
        with open(md_file_path, 'r', encoding='utf-8') as f:
            md_content = f.read()
        
        # Create new document
        doc = Document()
        
        # Set document properties
        doc.core_properties.title = f"{doc_type} - {os.path.basename(md_file_path).replace('.md', '')}"
        doc.core_properties.author = "JvG Consultancy via Kas"
        doc.core_properties.created = datetime.now()
        
        # Create header with branding
        self.create_document_header(doc, os.path.basename(md_file_path).replace('.md', ''), doc_type)
        
        # Process markdown content and convert to DOCX format
        self.process_markdown_content(doc, md_content)
        
        # Create footer
        doc_name = os.path.basename(md_file_path).replace('.md', '')
        self.create_document_footer(doc, doc_name)
        
        # Save document
        doc.save(output_docx_path)
        print(f"✅ Converted: {md_file_path} -> {output_docx_path}")
        
    def process_markdown_content(self, doc, md_content):
        """Process markdown content and apply formatting"""
        
        # Split content by sections
        sections = md_content.split('\n\n')
        
        current_heading_level = 0
        skip_next = False
        
        for section in sections:
            section = section.strip()
            if not section or skip_next:
                skip_next = False
                continue
                
            # Handle headings
            if section.startswith('# '):
                # Main heading (H1)
                heading_text = section[2:].strip()
                if heading_text.startswith('**'):
                    heading_text = heading_text[2:-2]
                para = doc.add_paragraph()
                para.text = heading_text
                para.style = 'Heading 1'
                # Set color to primary blue
                for run in para.runs:
                    run.font.color.rgb = RGBColor(0, 51, 102)  # #003366
                    run.font.bold = True
                    run.font.size = Pt(22)
                    
            elif section.startswith('## '):
                # H2 heading
                heading_text = section[3:].strip()
                if heading_text.startswith('**'):
                    heading_text = heading_text[2:-2]
                para = doc.add_paragraph()
                para.text = heading_text
                para.style = 'Heading 2'
                for run in para.runs:
                    run.font.color.rgb = RGBColor(0, 51, 102)  # #003366
                    run.font.bold = True
                    run.font.size = Pt(18)
                    
            elif section.startswith('### '):
                # H3 heading
                heading_text = section[4:].strip()
                if heading_text.startswith('**'):
                    heading_text = heading_text[2:-2]
                para = doc.add_paragraph()
                para.text = heading_text
                para.style = 'Heading 3'
                for run in para.runs:
                    run.font.color.rgb = RGBColor(0, 51, 102)  # #003366
                    run.font.bold = True
                    run.font.size = Pt(16)
                    
            elif section.startswith('****'):
                # Metadata section (skip processing but add spacing)
                skip_next = True
                
            elif re.match(r'^\|.*\|$', section):
                # Table
                self.add_table(doc, section)
                
            elif section.startswith('- ') or section.startswith('* '):
                # Bullet list
                self.add_bullet_list(doc, section)
                
            else:
                # Regular paragraph
                para = doc.add_paragraph(section)
                for run in para.runs:
                    run.font.color.rgb = RGBColor(31, 41, 55)  # #1F2937
                    run.font.name = 'Calibri'
                    run.font.size = Pt(11)
                    
        # Add page break at the end
        doc.add_page_break()
        
    def add_table(self, doc, table_content):
        """Add table from markdown table syntax"""
        # Parse markdown table
        lines = table_content.strip().split('\n')
        if len(lines) < 2:
            return
            
        # Count columns
        col_count = len(lines[0].split('|')) - 2
        
        # Create table
        table = doc.add_table(rows=len(lines), cols=col_count)
        table.style = 'Light Grid Accent 1'
        
        for i, line in enumerate(lines):
            cells = line.split('|')[1:-1]  # Remove first and last empty strings
            
            for j, cell_content in enumerate(cells):
                cell = table.cell(i, j)
                cell.text = cell_content.strip()
                
                # Format header row (second line typically contains dashes)
                if i == 1 and re.match(r'^[\s\-:]+$', cell_content.strip()):
                    # This is the header separator row, skip content
                    continue
                elif i == 0:
                    # Header row
                    for paragraph in cell.paragraphs:
                        for run in paragraph.runs:
                            run.font.bold = True
                            run.font.color.rgb = RGBColor(0, 51, 102)  # #003366
                            
    def add_bullet_list(self, doc, list_content):
        """Add bullet list from markdown bullet points"""
        items = []
        for line in list_content.split('\n'):
            line = line.strip()
            if line.startswith('- ') or line.startswith('* '):
                items.append(line[2:].strip())
                
        for item in items:
            para = doc.add_paragraph()
            para.style = 'List Bullet'
            para.add_run(item)
            for run in para.runs:
                run.font.color.rgb = RGBColor(31, 41, 55)  # #1F2937
                run.font.name = 'Calibri'
                run.font.size = Pt(11)

def main():
    """Main conversion function"""
    converter = DocxConverter()
    
    # Source directory
    source_dir = "/root/projects/jg/2026-pgs15-2025-phoenix-metals/deliverables/docx"
    
    # Working directory for conversion
    working_dir = "/root/projects/jg/2026-pgs15-2025-phoenix-metals/docx_working"
    
    # Target directory for final output
    target_dir = "/root/projects/jg/2026-pgs15-2025-phoenix-metals/deliverables/docx"
    
    # List of MD files to convert
    md_files = [
        "procedure_opslag_gevaarlijke_stoffen_v1.0.md",
        "beleidsdocument_opslagveiligheid_v1.0.md", 
        "kennisdossier_pgs15_2025_v1.0.md",
        "basishandleiding_medewerkers_v1.0.md",
        "werkinstructie_opslag_hzinnen_v1.0.md",
        "compliance_toets_pgs15_v1.0.md",
        "audit_checklist_rapport_v1.0.md",
        "niveaubepaling_rapport_v1.0.md",
        "eindrapport_project_v1.0.md"
    ]
    
    # Convert each file
    for md_file in md_files:
        md_path = os.path.join(source_dir, md_file)
        
        if os.path.exists(md_path):
            # Determine document type based on filename
            doc_type = "Procedure" if "procedure" in md_file.lower() else \
                       "Beleidsdocument" if "beleid" in md_file.lower() else \
                       "Rapport" if "rapport" in md_file.lower() else \
                       "Kennisdossier" if "kennisdossier" in md_file.lower() else \
                       "Werkinstructie" if "werkinstructie" in md_file.lower() else \
                       "Checklist" if "checklist" in md_file.lower() else "Document"
            
            # Convert file
            docx_filename = md_file.replace('.md', '_v1.0.docx')
            output_path = os.path.join(working_dir, docx_filename)
            
            try:
                converter.convert_markdown_to_docx(md_path, output_path, doc_type)
            except Exception as e:
                print(f"❌ Error converting {md_file}: {str(e)}")
                
    print(f"✅ Conversion completed. Files saved in: {working_dir}")

if __name__ == "__main__":
    main()