"""
PDF export for timetables — notice-board format.
Uses reportlab (pure-Python, no wkhtmltopdf required).
"""
from io import BytesIO
from reportlab.lib.pagesizes import A4, landscape
from reportlab.lib import colors
from reportlab.lib.units import cm
from reportlab.platypus import (
    SimpleDocTemplate, Table, TableStyle, Paragraph, Spacer, HRFlowable
)
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.enums import TA_CENTER, TA_LEFT

BRAND_COLOR = colors.HexColor("#1a56db")
ACCENT = colors.HexColor("#e3f0ff")
HEADER_BG = colors.HexColor("#1e3a5f")
FREE_COLOR = colors.HexColor("#f0f0f0")
BREAK_COLOR = colors.HexColor("#ffe4b5")
BRAND_FOOTER = "Powered by EduEval • Free School Management Platform • edueval.in"


def _subject_color(subj_type: str):
    return {
        "lab": colors.HexColor("#d1fae5"),
        "PT": colors.HexColor("#fef9c3"),
        "activity": colors.HexColor("#fce7f3"),
    }.get(subj_type, colors.white)


def export_class_timetable_pdf(
    school_name: str,
    grade: str,
    section: str,
    days: list[str],
    periods: list[int],
    grid: dict,           # grid[(day,period)] = {subj, teacher, type, is_break, is_free}
    academic_year: str = "2025-26",
) -> bytes:
    buf = BytesIO()
    doc = SimpleDocTemplate(
        buf,
        pagesize=landscape(A4),
        leftMargin=1.2 * cm,
        rightMargin=1.2 * cm,
        topMargin=1.2 * cm,
        bottomMargin=1.5 * cm,
    )

    styles = getSampleStyleSheet()
    title_style = ParagraphStyle(
        "title", fontName="Helvetica-Bold", fontSize=16,
        textColor=HEADER_BG, alignment=TA_CENTER, spaceAfter=2
    )
    sub_style = ParagraphStyle(
        "sub", fontName="Helvetica", fontSize=10,
        textColor=colors.grey, alignment=TA_CENTER, spaceAfter=6
    )
    cell_style = ParagraphStyle(
        "cell", fontName="Helvetica-Bold", fontSize=8,
        textColor=colors.HexColor("#1e3a5f"), alignment=TA_CENTER,
        leading=10
    )
    teacher_style = ParagraphStyle(
        "teacher", fontName="Helvetica", fontSize=7,
        textColor=colors.grey, alignment=TA_CENTER
    )
    brand_style = ParagraphStyle(
        "brand", fontName="Helvetica", fontSize=7,
        textColor=colors.HexColor("#888888"), alignment=TA_CENTER
    )

    story = []

    # Title
    story.append(Paragraph(school_name, title_style))
    story.append(Paragraph(
        f"Class Timetable — Grade {grade} Section {section} | AY {academic_year}",
        sub_style
    ))
    story.append(HRFlowable(width="100%", thickness=1, color=BRAND_COLOR, spaceAfter=8))

    # Build table data
    header_row = ["Period →\nDay ↓"] + [f"P{p}" for p in periods]
    data = [header_row]
    style_cmds = [
        ("BACKGROUND", (0, 0), (-1, 0), HEADER_BG),
        ("TEXTCOLOR", (0, 0), (-1, 0), colors.white),
        ("FONTNAME", (0, 0), (-1, 0), "Helvetica-Bold"),
        ("FONTSIZE", (0, 0), (-1, 0), 8),
        ("ALIGN", (0, 0), (-1, -1), "CENTER"),
        ("VALIGN", (0, 0), (-1, -1), "MIDDLE"),
        ("GRID", (0, 0), (-1, -1), 0.5, colors.HexColor("#cccccc")),
        ("ROWBACKGROUNDS", (0, 1), (-1, -1), [colors.white, ACCENT]),
        ("FONTNAME", (0, 1), (0, -1), "Helvetica-Bold"),
        ("BACKGROUND", (0, 1), (0, -1), HEADER_BG),
        ("TEXTCOLOR", (0, 1), (0, -1), colors.white),
    ]

    for row_i, day in enumerate(days, start=1):
        row = [Paragraph(f"<b>{day}</b>", ParagraphStyle(
            "dh", fontName="Helvetica-Bold", fontSize=8,
            textColor=colors.white, alignment=TA_CENTER
        ))]
        for col_i, period in enumerate(periods, start=1):
            cell = grid.get((day, period), {})
            if cell.get("is_break"):
                p = Paragraph("☕ BREAK", ParagraphStyle(
                    "brk", fontName="Helvetica-Bold", fontSize=7,
                    textColor=colors.HexColor("#7c4500"), alignment=TA_CENTER
                ))
                style_cmds.append(
                    ("BACKGROUND", (col_i, row_i), (col_i, row_i), BREAK_COLOR)
                )
                row.append(p)
            elif cell.get("is_free") or not cell:
                p = Paragraph("FREE", ParagraphStyle(
                    "free", fontName="Helvetica", fontSize=7,
                    textColor=colors.grey, alignment=TA_CENTER
                ))
                style_cmds.append(
                    ("BACKGROUND", (col_i, row_i), (col_i, row_i), FREE_COLOR)
                )
                row.append(p)
            else:
                bg = _subject_color(cell.get("subj_type", "theory"))
                style_cmds.append(
                    ("BACKGROUND", (col_i, row_i), (col_i, row_i), bg)
                )
                content = Paragraph(
                    f"<b>{cell.get('subject', '')}</b><br/>"
                    f"<font size='6'>{cell.get('teacher', '')}</font>",
                    cell_style
                )
                row.append(content)
        data.append(row)

    col_width = 2.6 * cm
    col_widths = [2.2 * cm] + [col_width] * len(periods)
    t = Table(data, colWidths=col_widths, rowHeights=[1.0 * cm] * len(data))
    t.setStyle(TableStyle(style_cmds))
    story.append(t)

    story.append(Spacer(1, 0.4 * cm))
    story.append(HRFlowable(width="100%", thickness=0.5, color=colors.lightgrey))
    story.append(Spacer(1, 0.1 * cm))
    story.append(Paragraph(BRAND_FOOTER, brand_style))

    doc.build(story)
    return buf.getvalue()


def export_teacher_timetable_pdf(
    school_name: str,
    teacher_name: str,
    days: list[str],
    periods: list[int],
    grid: dict,
    academic_year: str = "2025-26",
) -> bytes:
    buf = BytesIO()
    doc = SimpleDocTemplate(
        buf,
        pagesize=landscape(A4),
        leftMargin=1.2 * cm, rightMargin=1.2 * cm,
        topMargin=1.2 * cm, bottomMargin=1.5 * cm,
    )
    styles = getSampleStyleSheet()
    title_style = ParagraphStyle(
        "t", fontName="Helvetica-Bold", fontSize=15,
        textColor=HEADER_BG, alignment=TA_CENTER, spaceAfter=2
    )
    sub_style = ParagraphStyle(
        "s", fontName="Helvetica", fontSize=10,
        textColor=colors.grey, alignment=TA_CENTER, spaceAfter=6
    )
    brand_style = ParagraphStyle(
        "b", fontName="Helvetica", fontSize=7,
        textColor=colors.HexColor("#888888"), alignment=TA_CENTER
    )

    story = [
        Paragraph(school_name, title_style),
        Paragraph(f"Teacher Timetable — {teacher_name} | AY {academic_year}", sub_style),
        HRFlowable(width="100%", thickness=1, color=BRAND_COLOR, spaceAfter=8),
    ]

    header_row = ["Period →\nDay ↓"] + [f"P{p}" for p in periods]
    data = [header_row]
    style_cmds = [
        ("BACKGROUND", (0, 0), (-1, 0), HEADER_BG),
        ("TEXTCOLOR", (0, 0), (-1, 0), colors.white),
        ("FONTNAME", (0, 0), (-1, 0), "Helvetica-Bold"),
        ("FONTSIZE", (0, 0), (-1, 0), 8),
        ("ALIGN", (0, 0), (-1, -1), "CENTER"),
        ("VALIGN", (0, 0), (-1, -1), "MIDDLE"),
        ("GRID", (0, 0), (-1, -1), 0.5, colors.HexColor("#cccccc")),
        ("FONTNAME", (0, 1), (0, -1), "Helvetica-Bold"),
        ("BACKGROUND", (0, 1), (0, -1), HEADER_BG),
        ("TEXTCOLOR", (0, 1), (0, -1), colors.white),
    ]

    for row_i, day in enumerate(days, start=1):
        row = [Paragraph(f"<b>{day}</b>", ParagraphStyle(
            "dh", fontName="Helvetica-Bold", fontSize=8,
            textColor=colors.white, alignment=TA_CENTER
        ))]
        for col_i, period in enumerate(periods, start=1):
            cell = grid.get((day, period), {})
            if cell.get("is_break"):
                row.append(Paragraph("BREAK", ParagraphStyle(
                    "brk", fontName="Helvetica", fontSize=7,
                    textColor=colors.grey, alignment=TA_CENTER
                )))
                style_cmds.append(("BACKGROUND", (col_i, row_i), (col_i, row_i), BREAK_COLOR))
            elif not cell:
                row.append(Paragraph("FREE", ParagraphStyle(
                    "free", fontName="Helvetica", fontSize=7,
                    textColor=colors.lightgrey, alignment=TA_CENTER
                )))
                style_cmds.append(("BACKGROUND", (col_i, row_i), (col_i, row_i), FREE_COLOR))
            else:
                style_cmds.append(("BACKGROUND", (col_i, row_i), (col_i, row_i),
                                   _subject_color(cell.get("subj_type", "theory"))))
                row.append(Paragraph(
                    f"<b>{cell.get('subject', '')}</b><br/>"
                    f"<font size='6'>Gr.{cell.get('grade', '')}-{cell.get('section', '')}</font>",
                    ParagraphStyle("cs", fontName="Helvetica-Bold", fontSize=8,
                                   textColor=HEADER_BG, alignment=TA_CENTER, leading=10)
                ))
        data.append(row)

    col_width = 2.6 * cm
    t = Table(data, colWidths=[2.2 * cm] + [col_width] * len(periods),
              rowHeights=[1.0 * cm] * len(data))
    t.setStyle(TableStyle(style_cmds))
    story += [t, Spacer(1, 0.4 * cm),
              HRFlowable(width="100%", thickness=0.5, color=colors.lightgrey),
              Spacer(1, 0.1 * cm),
              Paragraph(BRAND_FOOTER, brand_style)]

    doc.build(story)
    return buf.getvalue()
