import sys, re, textwrap
sys.path.extend(['/usr/local/lib/python3.13/dist-packages','/usr/lib/python3/dist-packages','/opt/pyvenv/lib/python3.13/site-packages'])
from pathlib import Path
from reportlab.lib import colors
from reportlab.lib.enums import TA_LEFT
from reportlab.lib.pagesizes import A4
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.units import cm
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle, PageBreak, Preformatted

FONT = '/usr/share/fonts/truetype/dejavu/DejaVuSerif.ttf'
FONT_BOLD = '/usr/share/fonts/truetype/dejavu/DejaVuSerif-Bold.ttf'
pdfmetrics.registerFont(TTFont('DejaVuSerif', FONT))
pdfmetrics.registerFont(TTFont('DejaVuSerif-Bold', FONT_BOLD))

styles = getSampleStyleSheet()
styles.add(ParagraphStyle(name='KTitle', parent=styles['Title'], fontName='DejaVuSerif-Bold', fontSize=18, leading=23, spaceAfter=16))
styles.add(ParagraphStyle(name='KH1', parent=styles['Heading1'], fontName='DejaVuSerif-Bold', fontSize=15, leading=19, spaceBefore=14, spaceAfter=8))
styles.add(ParagraphStyle(name='KH2', parent=styles['Heading2'], fontName='DejaVuSerif-Bold', fontSize=12.5, leading=16, spaceBefore=10, spaceAfter=6))
styles.add(ParagraphStyle(name='KBody', parent=styles['BodyText'], fontName='DejaVuSerif', fontSize=10, leading=14, alignment=TA_LEFT, spaceAfter=6))
styles.add(ParagraphStyle(name='KMono', parent=styles['BodyText'], fontName='Courier', fontSize=8.5, leading=10.5, leftIndent=10, backColor=colors.whitesmoke, borderColor=colors.lightgrey, borderWidth=0.25, borderPadding=4, spaceAfter=8))


def clean_inline(text):
    text = text.replace('**', '')
    text = text.replace('`', '')
    text = text.replace('\\[', '').replace('\\]', '')
    text = text.replace('\\qquad', '    ').replace('\\frac', 'frac')
    return text


def make_pdf(md_path: Path):
    out_pdf = md_path.with_suffix('.pdf')
    doc = SimpleDocTemplate(str(out_pdf), pagesize=A4, rightMargin=1.4*cm, leftMargin=1.4*cm, topMargin=1.4*cm, bottomMargin=1.4*cm)
    flow = []
    lines = md_path.read_text(encoding='utf-8').splitlines()
    i = 0
    first_title = True
    while i < len(lines):
        line = lines[i].rstrip()
        if not line:
            i += 1
            continue
        if line.startswith('# '):
            if not first_title:
                flow.append(PageBreak())
            flow.append(Paragraph(clean_inline(line[2:]), styles['KTitle']))
            first_title = False
        elif line.startswith('## '):
            flow.append(Paragraph(clean_inline(line[3:]), styles['KH1']))
        elif line.startswith('### '):
            flow.append(Paragraph(clean_inline(line[4:]), styles['KH2']))
        elif line.startswith('|'):
            table_lines = []
            while i < len(lines) and lines[i].startswith('|'):
                table_lines.append(lines[i])
                i += 1
            rows = []
            for tl in table_lines:
                if set(tl.replace('|','').strip()) <= set('-: '):
                    continue
                cells = [clean_inline(c.strip()) for c in tl.strip('|').split('|')]
                rows.append(cells)
            if rows:
                tbl = Table(rows, repeatRows=1)
                tbl.setStyle(TableStyle([
                    ('FONTNAME', (0,0), (-1,-1), 'DejaVuSerif'),
                    ('FONTNAME', (0,0), (-1,0), 'DejaVuSerif-Bold'),
                    ('FONTSIZE', (0,0), (-1,-1), 8.3),
                    ('BACKGROUND', (0,0), (-1,0), colors.HexColor('#E2E8F0')),
                    ('GRID', (0,0), (-1,-1), 0.25, colors.grey),
                    ('VALIGN', (0,0), (-1,-1), 'TOP'),
                    ('LEFTPADDING', (0,0), (-1,-1), 4),
                    ('RIGHTPADDING', (0,0), (-1,-1), 4),
                ]))
                flow.append(tbl)
                flow.append(Spacer(1, 6))
            continue
        elif line.startswith('```'):
            code = []
            i += 1
            while i < len(lines) and not lines[i].startswith('```'):
                code.append(lines[i])
                i += 1
            flow.append(Preformatted('\n'.join(code), styles['KMono']))
        elif line.startswith('- '):
            flow.append(Paragraph('• ' + clean_inline(line[2:]), styles['KBody']))
        elif re.match(r'\d+\. ', line):
            flow.append(Paragraph(clean_inline(line), styles['KBody']))
        else:
            para = [line]
            j = i + 1
            while j < len(lines) and lines[j].strip() and not lines[j].startswith(('#', '|', '- ', '```')):
                para.append(lines[j].strip())
                j += 1
            text = clean_inline(' '.join(para))
            if text:
                flow.append(Paragraph(text, styles['KBody']))
            i = j - 1
        i += 1
    doc.build(flow)
    return out_pdf

if __name__ == '__main__':
    for arg in sys.argv[1:]:
        print(make_pdf(Path(arg)))
