from pathlib import Path
import re
from reportlab.lib import colors
from reportlab.lib.enums import TA_CENTER, TA_LEFT
from reportlab.lib.pagesizes import A4
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.units import cm
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle, PageBreak
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.pdfbase import pdfmetrics

BASE = Path('/data/workspace/outsourcing-initiative')
TEXT_PATH = BASE / '03-analysis/user_guide_eba_bce_translation_text_2026-06-30.txt'
OUT_DIR = BASE / '04-outputs'
OUT_DIR.mkdir(parents=True, exist_ok=True)
OUT_PDF = OUT_DIR / 'User Guide EBA Register and BCE Report_English_Translation_2026-06-30.pdf'
CANONICAL = BASE / '02-bank-documents/ISP Documentation/User Guide/User Guide EBA Register and BCE Report_English_Version.pdf'

text = TEXT_PATH.read_text(encoding='utf-8')

styles = getSampleStyleSheet()
styles.add(ParagraphStyle(name='CoverTitle', parent=styles['Title'], fontSize=22, leading=26, alignment=TA_CENTER, spaceAfter=18, textColor=colors.HexColor('#1F4E79')))
styles.add(ParagraphStyle(name='DocSubTitle', parent=styles['Title'], fontSize=16, leading=20, alignment=TA_CENTER, spaceAfter=24, textColor=colors.HexColor('#333333')))
styles.add(ParagraphStyle(name='H1x', parent=styles['Heading1'], fontSize=14, leading=17, spaceBefore=12, spaceAfter=8, textColor=colors.HexColor('#1F4E79')))
styles.add(ParagraphStyle(name='H2x', parent=styles['Heading2'], fontSize=11.5, leading=14, spaceBefore=9, spaceAfter=5, textColor=colors.HexColor('#1F4E79')))
styles.add(ParagraphStyle(name='Bodyx', parent=styles['BodyText'], fontSize=8.8, leading=11.2, spaceAfter=4))
styles.add(ParagraphStyle(name='Smallx', parent=styles['BodyText'], fontSize=7.8, leading=9.5, spaceAfter=3))
styles.add(ParagraphStyle(name='Footx', parent=styles['BodyText'], fontSize=7.2, leading=8.5, textColor=colors.grey))

HEADER = 'INTESA SANPAOLO | User Guide - EBA Register and ECB Report | English version translated on 30/06/2026'

def esc(s):
    return (s.replace('&','&amp;').replace('<','&lt;').replace('>','&gt;')
            .replace('\n','<br/>'))

def para(s, style='Bodyx'):
    return Paragraph(esc(s), styles[style])

def make_table(rows, widths=None, header=True):
    data = [[para(c, 'Smallx') for c in row] for row in rows]
    t = Table(data, colWidths=widths, hAlign='LEFT', repeatRows=1 if header else 0)
    ts = [
        ('GRID', (0,0), (-1,-1), 0.35, colors.HexColor('#B7B7B7')),
        ('VALIGN', (0,0), (-1,-1), 'TOP'),
        ('LEFTPADDING', (0,0), (-1,-1), 4), ('RIGHTPADDING', (0,0), (-1,-1), 4),
        ('TOPPADDING', (0,0), (-1,-1), 3), ('BOTTOMPADDING', (0,0), (-1,-1), 3),
    ]
    if header:
        ts += [('BACKGROUND', (0,0), (-1,0), colors.HexColor('#D9EAF7')), ('TEXTCOLOR', (0,0), (-1,0), colors.HexColor('#1F4E79'))]
    t.setStyle(TableStyle(ts))
    return t

def page_cb(canvas, doc):
    canvas.saveState()
    canvas.setFont('Helvetica', 7.5)
    canvas.setFillColor(colors.HexColor('#666666'))
    canvas.drawString(1.5*cm, A4[1]-1.0*cm, HEADER)
    canvas.drawRightString(A4[0]-1.5*cm, 0.9*cm, f'Page {doc.page}')
    canvas.setStrokeColor(colors.HexColor('#1F4E79'))
    canvas.setLineWidth(0.5)
    canvas.line(1.5*cm, A4[1]-1.15*cm, A4[0]-1.5*cm, A4[1]-1.15*cm)
    canvas.restoreState()

story=[]
story.append(Spacer(1, 2.0*cm))
story.append(Paragraph('INTESA SANPAOLO', styles['CoverTitle']))
story.append(Paragraph('EBA Register and ECB Report', styles['CoverTitle']))
story.append(Paragraph('User Guide', styles['DocSubTitle']))
story.append(Paragraph('English Version', styles['DocSubTitle']))
story.append(make_table([['Edition','Document status'], ['07/2023','Source Italian edition'], ['30/06/2026','Translated into English']], widths=[4*cm, 10*cm]))
story.append(Spacer(1, 0.4*cm))
story.append(para('This document is a professional English translation of the Italian user guide “Registro EBA e report BCE - Guida Utente”. The translation preserves the operational meaning, procedural sequencing, and corporate documentation style for use by authorised internal users.'))
story.append(PageBreak())
story.append(Paragraph('Change History', styles['H1x']))
story.append(make_table([
    ['Edition','Change'],
    ['01/2021','First draft.'],
    ['08/2022','Added: link to the Jaggaer portal / Format Contract; reconciliation rows relating to the child assessment.'],
    ['12/2022','Added specialised audit profile.'],
    ['07/2023','Consistency checks and ECB report.'],
    ['30/06/2026','Translated into English.'],
], widths=[3*cm, 13*cm]))
story.append(Spacer(1, 0.35*cm))

# Build remaining body from after Contents line onward, excluding front matter already handled
body = text.split('Contents\n',1)[1]
# Add contents block first
contents, rest = body.split('\n\n1. Roles',1)
story.append(Paragraph('Contents', styles['H1x']))
for line in contents.strip().splitlines():
    story.append(para(line))
story.append(PageBreak())
rest = '1. Roles' + rest

lines = rest.splitlines()
i=0
while i < len(lines):
    line = lines[i].strip()
    if not line:
        story.append(Spacer(1, 0.08*cm)); i += 1; continue
    # tables starting with known header lines
    if line in ('Role / Profile | Authorisations through the Outsourcing Portal back-end','Prefix | Source / meaning','Condition | System behaviour / required value','Fields | Control'):
        rows=[line.split(' | ')]
        i += 1
        while i < len(lines) and lines[i].strip() and not re.match(r'^(\d+(\.\d+)*\.?\s|[A-Z][A-Za-z ]+$|Monthly automatic extraction$|On-demand extraction$|Converting the \.txt)', lines[i].strip()):
            if ' | ' in lines[i]: rows.append(lines[i].split(' | ',1))
            else:
                if rows: rows[-1][-1] += ' ' + lines[i].strip()
            i += 1
        story.append(make_table(rows, widths=[5.1*cm, 10.9*cm]))
        continue
    if re.match(r'^\d+\.\s', line):
        story.append(Paragraph(esc(line), styles['H1x']))
    elif re.match(r'^\d+\.\d+', line) or line in ('Monthly automatic extraction','On-demand extraction','Converting the .txt extraction to Excel','Document control note'):
        story.append(Paragraph(esc(line), styles['H2x']))
    elif line.startswith('• '):
        story.append(Paragraph('&bull; ' + esc(line[2:]), styles['Bodyx']))
    else:
        story.append(para(line))
    i += 1

doc = SimpleDocTemplate(str(OUT_PDF), pagesize=A4, leftMargin=1.5*cm, rightMargin=1.5*cm, topMargin=1.6*cm, bottomMargin=1.35*cm, title='User Guide EBA Register and ECB Report - English Translation')
doc.build(story, onFirstPage=page_cb, onLaterPages=page_cb)

# Also update canonical bank-documents version with the same final PDF.
CANONICAL.parent.mkdir(parents=True, exist_ok=True)
CANONICAL.write_bytes(OUT_PDF.read_bytes())
print(OUT_PDF)
print(CANONICAL)
