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

doc = Document()

# --- Page margins ---
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)

# --- Style setup ---
style = doc.styles['Normal']
font = style.font
font.name = 'Calibri'
font.size = Pt(10.5)
font.color.rgb = RGBColor(0x33, 0x33, 0x33)
style.paragraph_format.space_after = Pt(6)
style.paragraph_format.line_spacing = 1.15

# Heading styles
for level, (size, color) in enumerate([(18, '1B3A5C'), (13, '1B3A5C'), (11, '2E5A88')], 1):
    hs = doc.styles[f'Heading {level}']
    hs.font.name = 'Calibri'
    hs.font.size = Pt(size)
    hs.font.color.rgb = RGBColor(*bytes.fromhex(color))
    hs.font.bold = True
    hs.paragraph_format.space_before = Pt(12 if level == 1 else 8)
    hs.paragraph_format.space_after = Pt(4)

# --- Logo ---
logo_path = '/root/projects/jg/assets/branding/jvg-consultancy-logo.png'
if os.path.exists(logo_path):
    doc.add_picture(logo_path, width=Cm(3.5))
    doc.paragraphs[-1].alignment = WD_ALIGN_PARAGRAPH.RIGHT
    doc.paragraphs[-1].paragraph_format.space_after = Pt(0)

# --- Title block ---
p = doc.add_paragraph()
p.alignment = WD_ALIGN_PARAGRAPH.LEFT
run = p.add_run('Management Samenvatting\nREACH Compliance')
run.font.size = Pt(22)
run.font.bold = True
run.font.color.rgb = RGBColor(0x1B, 0x3A, 0x5C)

p = doc.add_paragraph()
run = p.add_run('Phoenix Metals B.V. — Pilot Plant IJmuiden')
run.font.size = Pt(12)
run.font.color.rgb = RGBColor(0x2E, 0x5A, 0x88)
run.font.italic = True

p = doc.add_paragraph()
run = p.add_run('Vertrouwelijk — Directieteam\nApril 2026')
run.font.size = Pt(9)
run.font.color.rgb = RGBColor(0x88, 0x88, 0x88)

# --- Separator ---
p = doc.add_paragraph()
p.paragraph_format.space_before = Pt(2)
p.paragraph_format.space_after = Pt(8)
run = p.add_run('━' * 60)
run.font.size = Pt(6)
run.font.color.rgb = RGBColor(0xCC, 0xCC, 0xCC)

# --- Helper: add shaded table ---
def add_table(doc, headers, rows, col_widths=None):
    table = doc.add_table(rows=1 + len(rows), cols=len(headers))
    table.alignment = WD_TABLE_ALIGNMENT.CENTER
    table.style = 'Table Grid'
    
    # Header row
    hdr_color = '1B3A5C'
    for i, h in enumerate(headers):
        cell = table.rows[0].cells[i]
        cell.text = ''
        run = cell.paragraphs[0].add_run(h)
        run.font.bold = True
        run.font.size = Pt(9.5)
        run.font.color.rgb = RGBColor(0xFF, 0xFF, 0xFF)
        run.font.name = 'Calibri'
        cell.paragraphs[0].alignment = WD_ALIGN_PARAGRAPH.CENTER
        shading = parse_xml(f'<w:shd {nsdecls("w")} w:fill="{hdr_color}"/>')
        cell._tc.get_or_add_tcPr().append(shading)
    
    # Data rows
    for r_idx, row in enumerate(rows):
        bg = 'F5F7FA' if r_idx % 2 == 0 else 'FFFFFF'
        for c_idx, val in enumerate(row):
            cell = table.rows[r_idx + 1].cells[c_idx]
            cell.text = ''
            run = cell.paragraphs[0].add_run(str(val))
            run.font.size = Pt(9)
            run.font.name = 'Calibri'
            shading = parse_xml(f'<w:shd {nsdecls("w")} w:fill="{bg}"/>')
            cell._tc.get_or_add_tcPr().append(shading)
    
    if col_widths:
        for i, w in enumerate(col_widths):
            for row in table.rows:
                row.cells[i].width = Cm(w)
    
    return table

# --- 1. Context ---
doc.add_heading('1. Context', level=2)
p = doc.add_paragraph()
p.add_run('Phoenix Metals B.V. bereidt een pilot plant voor in IJmuiden (3.000L batch, 7.200 kg/jaar staalslakken) voor de extractie van vanadium uit twee afvalstromen: staalslakken (Tata Steel) en SARU ash (Shell). Het doel is TRL6 bereiken, FOAK-voorbereiding en JTF-subsidieverantwoording.').font.size = Pt(10.5)

# --- 2. Conclusie ---
doc.add_heading('2. Conclusie', level=2)
p = doc.add_paragraph()
p.add_run('De pilotfase is REACH-compliant haalbaar met minimale inspanning. ')
p.runs[-1].font.bold = True
p.add_run('De SR&D-uitsluiting geldt automatisch voor stoffen < 1 ton/jaar. PPORD-notificatie bij ECHA is nodig zodra de vanadium-productie ≥ 1 ton/jaar nadert. Het Vanadium Consortium biedt een kostenbesparende meelift-optie via een Letter of Access (LoA). Volledige REACH-registratie is pas vereist bij FOAK-schaal (geschat €120K–€290K).')

# --- 3. Statusoverzicht ---
doc.add_heading('3. Statusoverzicht per stroom', level=2)
add_table(doc,
    ['Stroom', 'REACH-status', 'Actie nodig', 'Urgentie'],
    [
        ['Staalslakken (Tata)', 'Afvalstof → vrijgesteld', 'End-of-waste bepalen', 'Medium'],
        ['SARU ash (Shell)', 'Afvalstof → vrijgesteld', 'Stralingswetgeving is prioriteit', 'Laag'],
        ['Invoerchemicaliën (4×)', 'Reeds geregistreerd', 'SDS op orde houden', 'Laag'],
        ['Vanadium-producten', 'Niet geregistreerd', 'PPORD of Consortium LoA', 'Hoog'],
        ['Secundaire producten', 'Reeds geregistreerd', 'Monitoren bij opschaling', 'Laag'],
    ],
    col_widths=[4.5, 4, 4.5, 2]
)

# --- 4. Drie Keuzes ---
doc.add_heading('4. Drie Keuzes voor het Management', level=2)

choices = [
    ('Vanadium Consortium aansluiten',
     'Full membership (€15K–€40K) of Letter of Access (goedkoper). Aanbevolen: LoA voor pilotfase, membership bij FOAK.'),
    ('PPORD-notificatie indienen bij ECHA',
     'Verplicht als vanadium-productie ≥ 1 ton/jaar. 5 jaar geldig. Kan zelf of via consultant.'),
    ('Volume-monitoring implementeren',
     'Kwartaallijks bijhouden per stof om REACH-drempels (1 ton/jaar) te bewaken.'),
]

for i, (title, desc) in enumerate(choices, 1):
    p = doc.add_paragraph()
    run = p.add_run(f'{i}. {title}')
    run.font.bold = True
    run.font.size = Pt(10.5)
    run.font.color.rgb = RGBColor(0x1B, 0x3A, 0x5C)
    p2 = doc.add_paragraph(desc)
    p2.paragraph_format.left_indent = Cm(0.5)
    p2.paragraph_format.space_after = Pt(4)

# --- 5. Tijdlijn ---
doc.add_heading('5. Tijdlijn', level=2)
add_table(doc,
    ['Periode', 'Actie', 'Kosten'],
    [
        ['Q2 2026', 'Consortium verkennen + LoA aanvragen', '€5K–€15K'],
        ['Q3 2026', 'PPORD-notificatie indienen (indien ≥1 ton)', '€1.5K–€5K'],
        ['Q4 2026', 'Volume-monitoring + SDS-update', 'Intern'],
        ['2027–2028', 'FOAK REACH-registratie voorbereiden', '€120K–€290K'],
    ],
    col_widths=[3, 7, 3.5]
)

# --- 6. Budget ---
doc.add_heading('6. Budgetindicatie', level=2)

budget_items = [
    ('Pilotfase:', '€6.500 – €20.000', '(LoA + PPORD + monitoring)'),
    ('FOAK-fase:', '€120.000 – €290.000', '(volledige registratie + consortium + CSR)'),
    ('Totaal traject:', '€126.500 – €310.000', ''),
]
for label, amount, note in budget_items:
    p = doc.add_paragraph()
    run = p.add_run(label + ' ')
    run.font.bold = True
    run.font.size = Pt(10.5)
    run = p.add_run(amount + ' ')
    run.font.bold = True
    run.font.color.rgb = RGBColor(0x1B, 0x3A, 0x5C)
    if note:
        run = p.add_run(note)
        run.font.size = Pt(9.5)
        run.font.color.rgb = RGBColor(0x66, 0x66, 0x66)
    p.paragraph_format.space_after = Pt(2)

# --- Footer ---
doc.add_paragraph()
p = doc.add_paragraph()
run = p.add_run('━' * 60)
run.font.size = Pt(6)
run.font.color.rgb = RGBColor(0xCC, 0xCC, 0xCC)

p = doc.add_paragraph()
p.alignment = WD_ALIGN_PARAGRAPH.CENTER
run = p.add_run('JvG Consultancy — Vertrouwelijk')
run.font.size = Pt(8)
run.font.color.rgb = RGBColor(0x99, 0x99, 0x99)
run.font.italic = True

# --- Save ---
out = '/root/projects/jg/2026-reach-phoenix-metals/deliverables/docx/REACH_Management_Samenvatting_Phoenix_Metals_v1.0.docx'
doc.save(out)
print(f'OK: {out}')
