#!/usr/bin/env python3
"""
Generate CHCFC Windows Laptop Quick-Start Guide PDF.
Follows CHCFC branding guidelines and all user instructions:
- Congratulations on getting a CHCFC Windows laptop.
- Top section: OpenVPN Connect guide (open, press connect, first.last, Windows password).
- Storage policy: Do NOT store files locally (Desktop, Documents, Downloads, etc.).
  Please reference health center policies for official guidelines on data transmission and storage.
- Network drives: N: is shared / department files; H: is home / private user files.
- Email policy: Do NOT use Outlook desktop app; use webmail.chcfc.org (accessible via Portal on desktop).
  Sign in using entire email address and Windows domain password.
- Reason: Migrating away from on-prem Exchange to M365 accounts.
- Help Desk contact: helpdesk@chcfc.org
"""

import os
from reportlab.lib.pagesizes import letter
from reportlab.lib import colors
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.platypus import (
    SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle, Image, HRFlowable, KeepTogether
)
from reportlab.pdfgen import canvas

PDF_OUTPUT_PATH = "/mnt/docker/httpd-ficit-files/CHCFC Windows Laptop Quick-Start Guide.pdf"
LOGO_PATH = "/mnt/docker/httpd-ficit-files/Design-Elements/Logo/Primary Logo-no background.png"

# Color Palette
PRIMARY_TEAL = colors.HexColor("#0f766e")      # Deep Emerald / Teal
ACCENT_GREEN = colors.HexColor("#059669")      # Green
DARK_SLATE   = colors.HexColor("#1e293b")      # Text Dark
MUTED_TEXT   = colors.HexColor("#475569")      # Slate 600
LIGHT_BG     = colors.HexColor("#f8fafc")      # Slate 50
BORDER_COLOR = colors.HexColor("#cbd5e1")      # Slate 300
HIGHLIGHT_BG = colors.HexColor("#f0fdf4")      # Mint / Emerald 50
WARN_BG      = colors.HexColor("#fef2f2")      # Red 50
WARN_BORDER  = colors.HexColor("#f87171")      # Red 400
WARN_TEXT    = colors.HexColor("#991b1b")      # Red 800
INFO_BG      = colors.HexColor("#f0f9ff")      # Sky 50
INFO_BORDER  = colors.HexColor("#38bdf8")      # Sky 400

class NumberedCanvas(canvas.Canvas):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self._saved_page_states = []

    def showPage(self):
        self._saved_page_states.append(dict(self.__dict__))
        self._startPage()

    def save(self):
        num_pages = len(self._saved_page_states)
        for state in self._saved_page_states:
            self.__dict__.update(state)
            self.draw_page_decorations(num_pages)
            super().showPage()
        super().save()

    def draw_page_decorations(self, total_pages):
        self.saveState()
        
        # Header accent bar (top border)
        self.setFillColor(PRIMARY_TEAL)
        self.rect(36, 792 - 12, 612 - 72, 4, fill=1, stroke=0)
        
        # Footer
        self.setFont("Helvetica", 8)
        self.setFillColor(MUTED_TEXT)
        footer_text = "Community Health Center of Franklin County (CHCFC)  |  IT Support: helpdesk@chcfc.org"
        self.drawString(36, 24, footer_text)
        
        page_num_str = f"Page {self._pageNumber} of {total_pages}"
        self.drawRightString(612 - 36, 24, page_num_str)
        
        # Footer thin line
        self.setStrokeColor(BORDER_COLOR)
        self.setLineWidth(0.5)
        self.line(36, 36, 612 - 36, 36)
        
        self.restoreState()


def build_pdf():
    # Page setup: letter is 612 x 792 points. Margins: 36 pt (0.5 in) left/right, 24 pt top, 42 pt bottom
    doc = SimpleDocTemplate(
        PDF_OUTPUT_PATH,
        pagesize=letter,
        leftMargin=36,
        rightMargin=36,
        topMargin=26,
        bottomMargin=46
    )

    styles = getSampleStyleSheet()
    
    # Custom Typography
    title_style = ParagraphStyle(
        'DocTitle',
        parent=styles['Normal'],
        fontName='Helvetica-Bold',
        fontSize=17,
        leading=21,
        textColor=PRIMARY_TEAL
    )
    
    subtitle_style = ParagraphStyle(
        'DocSubTitle',
        parent=styles['Normal'],
        fontName='Helvetica',
        fontSize=10,
        leading=13,
        textColor=MUTED_TEXT
    )
    
    welcome_banner_style = ParagraphStyle(
        'WelcomeBanner',
        parent=styles['Normal'],
        fontName='Helvetica-Bold',
        fontSize=11,
        leading=15,
        textColor=PRIMARY_TEAL
    )
    
    welcome_body_style = ParagraphStyle(
        'WelcomeBody',
        parent=styles['Normal'],
        fontName='Helvetica',
        fontSize=9,
        leading=13,
        textColor=DARK_SLATE
    )
    
    section_h1 = ParagraphStyle(
        'SectionH1',
        parent=styles['Normal'],
        fontName='Helvetica-Bold',
        fontSize=12,
        leading=16,
        textColor=PRIMARY_TEAL,
        spaceAfter=4
    )

    body_text = ParagraphStyle(
        'BodyTextCustom',
        parent=styles['Normal'],
        fontName='Helvetica',
        fontSize=8.5,
        leading=12,
        textColor=DARK_SLATE
    )
    
    body_bold = ParagraphStyle(
        'BodyBoldCustom',
        parent=styles['Normal'],
        fontName='Helvetica-Bold',
        fontSize=8.5,
        leading=12,
        textColor=DARK_SLATE
    )

    story = []

    # 1. Header with Logo and Title
    logo_img = Image(LOGO_PATH, width=170, height=59.2)
    logo_img.hAlign = 'LEFT'
    
    header_title_cell = [
        Paragraph("Welcome to Your CHCFC Windows Laptop", title_style),
        Spacer(1, 3),
        Paragraph("Essential Setup, Network Access, Data Storage & Email Guidelines", subtitle_style),
    ]
    
    header_table = Table(
        [[header_title_cell, logo_img]],
        colWidths=[355, 185]
    )
    header_table.setStyle(TableStyle([
        ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
        ('LEFTPADDING', (0, 0), (-1, -1), 0),
        ('RIGHTPADDING', (0, 0), (-1, -1), 0),
        ('TOPPADDING', (0, 0), (-1, -1), 0),
        ('BOTTOMPADDING', (0, 0), (-1, -1), 0),
    ]))
    story.append(header_table)
    story.append(Spacer(1, 8))

    # 2. Congratulations Banner Box
    congrats_content = [
        Paragraph("Congratulations on receiving your new CHCFC Windows laptop!", welcome_banner_style),
        Spacer(1, 3),
        Paragraph(
            "This enterprise workstation has been pre-configured by the IT Department with all required tools, "
            "security software, and corporate shortcuts. Please review this quick-start guide to ensure seamless "
            "remote connectivity, proper file preservation, and smooth daily workflow.",
            welcome_body_style
        )
    ]
    congrats_box = Table([[congrats_content]], colWidths=[540])
    congrats_box.setStyle(TableStyle([
        ('BACKGROUND', (0, 0), (-1, -1), HIGHLIGHT_BG),
        ('BOX', (0, 0), (-1, -1), 1, ACCENT_GREEN),
        ('TOPPADDING', (0, 0), (-1, -1), 8),
        ('BOTTOMPADDING', (0, 0), (-1, -1), 8),
        ('LEFTPADDING', (0, 0), (-1, -1), 10),
        ('RIGHTPADDING', (0, 0), (-1, -1), 10),
    ]))
    story.append(congrats_box)
    story.append(Spacer(1, 10))

    # 3. SECTION 1 (TOP): Connecting Remotely with OpenVPN Connect
    vpn_header = Paragraph("1. Remote Connectivity: OpenVPN Connect (First Step Offsite)", section_h1)
    
    vpn_steps_content = [
        Paragraph("Whenever you work outside a CHCFC clinic or office, you must connect to the VPN to access your network drives, webmail, and internal systems:", body_text),
        Spacer(1, 4),
        Paragraph("<b>Step 1: Open the Application</b><br/>"
                  "Locate and launch <b>OpenVPN Connect</b> from your Desktop or the Windows Start menu (look for the orange and white circular icon).", body_text),
        Spacer(1, 3),
        Paragraph("<b>Step 2: Connect to the Profile</b><br/>"
                  "Click the toggle switch or press <b>CONNECT</b> next to the pre-loaded <b>CHCFC</b> profile.", body_text),
        Spacer(1, 3),
        Paragraph("<b>Step 3: Enter Your Windows Credentials</b><br/>"
                  "  • <b>Username:</b> Enter your username formatted as <code>first.last</code> (e.g. <code>jane.doe</code>).<br/>"
                  "  • <b>Password:</b> Enter your standard Windows login / domain password.<br/>"
                  "  • Check <i>Remember password</i> if desired, then click <b>CONTINUE</b>.", body_text),
        Spacer(1, 3),
        Paragraph("<b>Step 4: Verify Connection</b><br/>"
                  "The status indicator will turn solid green and display <b>CONNECTED</b>. Your secure tunnel to CHCFC servers is now active.", body_text),
    ]
    
    vpn_box = Table([[vpn_steps_content]], colWidths=[540])
    vpn_box.setStyle(TableStyle([
        ('BACKGROUND', (0, 0), (-1, -1), INFO_BG),
        ('BOX', (0, 0), (-1, -1), 1, INFO_BORDER),
        ('TOPPADDING', (0, 0), (-1, -1), 8),
        ('BOTTOMPADDING', (0, 0), (-1, -1), 8),
        ('LEFTPADDING', (0, 0), (-1, -1), 10),
        ('RIGHTPADDING', (0, 0), (-1, -1), 10),
    ]))
    
    story.append(vpn_header)
    story.append(vpn_box)
    story.append(Spacer(1, 10))

    # 4. SECTION 2: Critical File Storage Policy (N: & H: Drives)
    storage_header = Paragraph("2. Critical File Storage Policy: Use N: and H: Drives ONLY", section_h1)
    
    warning_content = [
        Paragraph("<b>CRITICAL DATA WARNING — DO NOT STORE FILES LOCALLY ON THIS LAPTOP:</b>", ParagraphStyle(
            'WarnHeading', parent=body_bold, textColor=WARN_TEXT, fontSize=9
        )),
        Spacer(1, 2),
        Paragraph(
            "<b>Never save work or sensitive documents to the local hard drive (C: Drive).</b> This includes the <b>Desktop</b>, "
            "<b>My Documents</b>, <b>Downloads</b>, and <b>Pictures</b> folders. Local files are <u>NOT backed up</u>, are inaccessible "
            "from other computers, and will be permanently lost if your laptop is lost, damaged, repaired, or replaced.<br/>"
            "<i>Please reference health center policies for official guidelines on data transmission and storage.</i>",
            ParagraphStyle('WarnBody', parent=body_text, textColor=WARN_TEXT)
        )
    ]
    warning_box = Table([[warning_content]], colWidths=[540])
    warning_box.setStyle(TableStyle([
        ('BACKGROUND', (0, 0), (-1, -1), WARN_BG),
        ('BOX', (0, 0), (-1, -1), 1, WARN_BORDER),
        ('TOPPADDING', (0, 0), (-1, -1), 7),
        ('BOTTOMPADDING', (0, 0), (-1, -1), 7),
        ('LEFTPADDING', (0, 0), (-1, -1), 10),
        ('RIGHTPADDING', (0, 0), (-1, -1), 10),
    ]))

    drive_table_data = [
        [
            Paragraph("<b>Network Drive</b>", body_bold),
            Paragraph("<b>Purpose & Scope</b>", body_bold),
            Paragraph("<b>Usage Guidelines & Backup Status</b>", body_bold)
        ],
        [
            Paragraph("<b>N: Drive</b><br/><i>(Shared)</i>", body_text),
            Paragraph("<b>Shared Departmental & Clinic Data</b><br/>Accessible to authorized teams and colleagues.", body_text),
            Paragraph("Use for team projects, shared spreadsheets, forms, and clinical resources. Fully protected by automated nightly enterprise backups.", body_text)
        ],
        [
            Paragraph("<b>H: Drive</b><br/><i>(Home / Personal)</i>", body_text),
            Paragraph("<b>Private Individual Work Data</b><br/>Accessible exclusively by you.", body_text),
            Paragraph("Use for your personal work drafts, individual notes, and working files. Fully protected by automated nightly enterprise backups.", body_text)
        ],
        [
            Paragraph("<b>Local C: Drive</b><br/><i>(Desktop / Downloads)</i>", ParagraphStyle('RedLabel', parent=body_bold, textColor=WARN_TEXT)),
            Paragraph("<b>Device Local Storage ONLY</b><br/>Temporary machine cache.", body_text),
            Paragraph("<b>DO NOT STORE FILES HERE.</b> Not backed up. Move all downloads and desktop files into N: or H: drives immediately.", ParagraphStyle('RedNote', parent=body_text, textColor=WARN_TEXT))
        ]
    ]
    
    drive_table = Table(drive_table_data, colWidths=[105, 185, 250])
    drive_table.setStyle(TableStyle([
        ('BACKGROUND', (0, 0), (-1, 0), LIGHT_BG),
        ('LINEBELOW', (0, 0), (-1, 0), 1.2, PRIMARY_TEAL),
        ('GRID', (0, 0), (-1, -1), 0.5, BORDER_COLOR),
        ('VALIGN', (0, 0), (-1, -1), 'TOP'),
        ('TOPPADDING', (0, 0), (-1, -1), 5),
        ('BOTTOMPADDING', (0, 0), (-1, -1), 5),
        ('LEFTPADDING', (0, 0), (-1, -1), 6),
        ('RIGHTPADDING', (0, 0), (-1, -1), 6),
        ('BACKGROUND', (0, 3), (-1, 3), WARN_BG),
    ]))

    story.append(storage_header)
    story.append(warning_box)
    story.append(Spacer(1, 5))
    story.append(drive_table)
    story.append(Spacer(1, 10))

    # 5. SECTION 3: Email Access Policy (Webmail vs. Outlook & M365 Migration)
    email_header = Paragraph("3. Email Access Policy: Use Webmail (Moving to Microsoft 365)", section_h1)

    email_content = [
        Paragraph(
            "<b>DO NOT USE THE OUTLOOK DESKTOP APP:</b><br/>"
            "Please do not open or configure the desktop Microsoft Outlook client on this laptop. "
            "All staff should access their email through the browser at <b>webmail.chcfc.org</b>.",
            body_text
        ),
        Spacer(1, 4),
        Paragraph(
            "<b>How to Access Webmail:</b><br/>"
            "  1. Double-click the <b>CHCFC Portal</b> shortcut located on your desktop (or visit <code>https://portal.chcfc.org</code>).<br/>"
            "  2. Click the <b>Webmail</b> button (or browse directly to <code>https://webmail.chcfc.org</code>).<br/>"
            "  3. Log in with your <b>entire email address</b> (e.g. <code>firstname.lastname@chcfc.org</code>) and Windows domain password.",
            body_text
        ),
        Spacer(1, 4),
        Paragraph(
            "<b>Why We Are Phasing Out Outlook Desktop:</b><br/>"
            "CHCFC is actively transitioning away from legacy on-premises Exchange servers. Every employee will soon be receiving "
            "a modern <b>Microsoft 365 (M365)</b> cloud account. Utilizing the web interface ensures consistent email delivery, avoids "
            "profile corruption, and guarantees a seamless cutover when your mailbox is migrated to the cloud.",
            body_text
        )
    ]
    
    email_box = Table([[email_content]], colWidths=[540])
    email_box.setStyle(TableStyle([
        ('BACKGROUND', (0, 0), (-1, -1), LIGHT_BG),
        ('BOX', (0, 0), (-1, -1), 1, BORDER_COLOR),
        ('TOPPADDING', (0, 0), (-1, -1), 8),
        ('BOTTOMPADDING', (0, 0), (-1, -1), 8),
        ('LEFTPADDING', (0, 0), (-1, -1), 10),
        ('RIGHTPADDING', (0, 0), (-1, -1), 10),
    ]))
    
    story.append(KeepTogether([email_header, email_box]))
    story.append(Spacer(1, 10))

    # 6. SECTION 4: Hardware Care & IT Support Contacts
    care_header = Paragraph("4. Laptop Care & IT Support Contacts", section_h1)

    support_table_data = [
        [
            Paragraph("<b>Hardware Care — No Stickers:</b><br/>"
                      "Please do not apply adhesive stickers, decals, or tape to the laptop case, keyboard palm rest, or display bezel. "
                      "Laptops are clinical healthcare organization property and must remain clean, professional, and free of adhesive residue for sanitization and future redeployment.<br/><br/>"
                      "<b>Need Assistance?</b> Submit a ticket via email to <b>helpdesk@chcfc.org</b> or contact the CHCFC IT Help Desk.<br/>"
                      "<i>Tip: When requesting help offsite, please ensure OpenVPN Connect is active so technicians can assist remotely.</i>",
                      ParagraphStyle('HelpText', parent=body_text, fontSize=8, leading=11.5))
        ]
    ]
    support_box = Table(support_table_data, colWidths=[540])
    support_box.setStyle(TableStyle([
        ('BACKGROUND', (0, 0), (-1, -1), colors.HexColor("#f1f5f9")),
        ('BOX', (0, 0), (-1, -1), 0.5, BORDER_COLOR),
        ('TOPPADDING', (0, 0), (-1, -1), 8),
        ('BOTTOMPADDING', (0, 0), (-1, -1), 8),
        ('LEFTPADDING', (0, 0), (-1, -1), 10),
        ('RIGHTPADDING', (0, 0), (-1, -1), 10),
    ]))
    story.append(KeepTogether([care_header, support_box]))

    # Build the document using the customized canvas
    doc.build(story, canvasmaker=NumberedCanvas)
    print(f"Successfully generated PDF: {PDF_OUTPUT_PATH}")

if __name__ == '__main__':
    build_pdf()
