from pathlib import Path

from reportlab.lib import colors
from reportlab.lib.pagesizes import letter
from reportlab.lib.styles import ParagraphStyle, getSampleStyleSheet
from reportlab.lib.units import inch
from reportlab.platypus import Paragraph, SimpleDocTemplate, Spacer, Table, TableStyle


ROOT = Path(__file__).resolve().parents[1]
OUTPUT_DIR = ROOT / "output" / "pdf"
PDF_PATH = OUTPUT_DIR / "imrd-cota-app-summary.pdf"


def bullet_paragraphs(items, style):
    bullets = []
    for item in items:
        bullets.append(Paragraph(f"- {item}", style))
        bullets.append(Spacer(1, 0.03 * inch))
    return bullets[:-1]


def section(title, body, title_style, body_style):
    return [
        Paragraph(title, title_style),
        Spacer(1, 0.05 * inch),
        Paragraph(body, body_style),
        Spacer(1, 0.08 * inch),
    ]


def build_pdf():
    OUTPUT_DIR.mkdir(parents=True, exist_ok=True)

    doc = SimpleDocTemplate(
        str(PDF_PATH),
        pagesize=letter,
        leftMargin=0.58 * inch,
        rightMargin=0.58 * inch,
        topMargin=0.52 * inch,
        bottomMargin=0.5 * inch,
        title="IMRD Cota App Summary",
        author="OpenAI Codex",
    )

    styles = getSampleStyleSheet()
    title_style = ParagraphStyle(
        "Title",
        parent=styles["Heading1"],
        fontName="Helvetica-Bold",
        fontSize=19,
        leading=21,
        textColor=colors.HexColor("#17324D"),
        spaceAfter=2,
    )
    meta_style = ParagraphStyle(
        "Meta",
        parent=styles["BodyText"],
        fontName="Helvetica",
        fontSize=8.6,
        leading=10.2,
        textColor=colors.HexColor("#506070"),
        spaceAfter=8,
    )
    heading_style = ParagraphStyle(
        "Heading",
        parent=styles["Heading2"],
        fontName="Helvetica-Bold",
        fontSize=10.4,
        leading=12,
        textColor=colors.HexColor("#1F4E79"),
        spaceBefore=1,
        spaceAfter=2,
    )
    body_style = ParagraphStyle(
        "Body",
        parent=styles["BodyText"],
        fontName="Helvetica",
        fontSize=8.8,
        leading=10.8,
        textColor=colors.black,
    )
    bullet_style = ParagraphStyle(
        "Bullets",
        parent=body_style,
        leftIndent=3,
        firstLineIndent=0,
        spaceBefore=0,
        spaceAfter=0,
    )

    what_it_is = (
        "IMRD Cota is a role-based web portal for the Instituto Municipal de Recreacion y Deporte de Cota. "
        "The repo shows a public registration flow plus separate login and dashboard experiences for students, "
        "administrators, professors, and methodologists."
    )

    who_its_for = (
        "Primary persona: IMRD Cota sports school participant/applicant, with additional role-specific views for internal staff."
    )

    features = [
        "Public landing page with enrollment call-to-action, countdown, and modal registration form.",
        "Login flow that authenticates against an external webhook and redirects by returned user type.",
        "Student dashboard with review status, enrolled sports, announcements, and profile settings.",
        "Document correction ('Subsanar Documentos') flow with file upload for students under review.",
        "Administrator dashboard for browsing students, filtering records, viewing details, and editing student/course data.",
        "Forgot-username and password-change flows powered by external endpoints.",
        "Theme and language preferences stored locally in the browser for the student experience.",
    ]

    architecture = [
        "Client UI: independent route folders (`/login`, `/deportista`, `/administrador`, `/metodologo`, `/profesor`, `/funcionamiento`) each expose a single page entry (`index.php` or `index.php.html`).",
        "Frontend stack: pages rely on Tailwind via CDN, Google Fonts, browser JavaScript, and `sessionStorage`/`localStorage` for role, user ID, theme, and language state.",
        "Integration layer: browser `fetch` calls post JSON or multipart form data to multiple `https://n8n.nextgonsas.com.co/webhook/...` endpoints for auth, registration, student data, comments, corrections, communications, password reset, and service checks.",
        "Flow: public user opens the registration page or logs in, the browser stores returned identity data, then navigates to the role page which calls more webhooks to load or update data.",
        "Backend/data store: Not found in repo. No local API server, database schema, or deployment config is present.",
    ]

    how_to_run = [
        "No `README`, `composer.json`, `package.json`, or local start script was found in the repo.",
        "Serve the folder from a browser-accessible web root that can expose the included `.php` files as pages; the repo itself contains only page files and client-side scripts.",
        "Open `/index.php.html` for the public enrollment flow or `/login/` for authenticated access.",
        "Allow internet access to external dependencies used by the pages: Tailwind CDN, Google Fonts, image/Drive assets, and `n8n.nextgonsas.com.co` webhooks.",
    ]

    story = [
        Paragraph("IMRD Cota App Summary", title_style),
        Paragraph(
            "Repo evidence reviewed on 2026-04-07. Single-page summary generated from local files only.",
            meta_style,
        ),
    ]

    story += section("What It Is", what_it_is, heading_style, body_style)
    story += section("Who It's For", who_its_for, heading_style, body_style)
    left_column = [Paragraph("What It Does", heading_style), Spacer(1, 0.04 * inch)]
    left_column.extend(bullet_paragraphs(features, bullet_style))

    right_column = [Paragraph("How It Works", heading_style), Spacer(1, 0.04 * inch)]
    right_column.extend(bullet_paragraphs(architecture, bullet_style))

    columns = Table(
        [[left_column, right_column]],
        colWidths=[3.45 * inch, 3.45 * inch],
        hAlign="LEFT",
    )
    columns.setStyle(
        TableStyle(
            [
                ("VALIGN", (0, 0), (-1, -1), "TOP"),
                ("LEFTPADDING", (0, 0), (-1, -1), 0),
                ("RIGHTPADDING", (0, 0), (-1, -1), 12),
                ("TOPPADDING", (0, 0), (-1, -1), 0),
                ("BOTTOMPADDING", (0, 0), (-1, -1), 0),
            ]
        )
    )
    story.extend([columns, Spacer(1, 0.08 * inch)])
    story += section("How to Run", "<br/>".join(f"- {item}" for item in how_to_run), heading_style, bullet_style)

    doc.build(story)
    print(PDF_PATH)


if __name__ == "__main__":
    build_pdf()
