# generate_course_structure_pdf.py
# Course Structure for Department of International Relations & Diplomacy
# Peter University, Achina/Onneh

import re
from reportlab.lib.pagesizes import A4
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.units import mm
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle, PageBreak
from reportlab.lib.enums import TA_CENTER, TA_LEFT, TA_RIGHT, TA_JUSTIFY
from reportlab.lib.colors import HexColor, white, lightgrey, black

# -----------------------------------------------------------------------------
# CONFIGURATION
# -----------------------------------------------------------------------------
PROGRAMME_NAME = "DEPARTMENT OF INTERNATIONAL RELATIONS & DIPLOMACY"
FACULTY_NAME = "Faculty of Arts, Social & Management Sciences"
UNIVERSITY_NAME = "PETER UNIVERSITY, ACHINA/ONNEH"

# -----------------------------------------------------------------------------
# COURSE STRUCTURE DATA - DEPARTMENT OF INTERNATIONAL RELATIONS & DIPLOMACY
# Based on the provided DOCX file
# -----------------------------------------------------------------------------
COURSE_DATA = [
    {
        "level": "100 LEVEL",
        "semester": "FIRST SEMESTER",
        "courses": [
            ["GST 101", "Communication skills in English I", "2", "C", "15", "45"],
            ["GST 103", "Philosophy, Logic and Human existence", "2", "C", "30", "-"],
            ["PU-GST 111", "Leadership, Ethics and Development 1", "1", "C", "15", "-"],
            ["PU-GST 113", "Basic Igbo Language & Culture I", "1", "C", "15", "-"],
            ["PU-GST 115", "Introduction to Entrepreneurship Studies", "1", "C", "15", "-"],
            ["PU-GST 107", "History and Philosophy of Science", "2", "C", "30", "-"],
            ["PU-GST 105", "Humanities", "2", "C", "30", "-"],
            ["COS 101", "Introduction to Computing", "2", "C", "30", "-"],
            ["POL 101", "Introduction to Political Science I", "2", "C", "30", "-"],
            ["LAW 111", "Nigeria Legal system I", "1", "C", "15", "-"],
            ["IRS 107", "Ancestors of contemporary International System", "2", "C", "30", "-"],
            ["IRS 103", "Introduction to African Politics", "2", "C", "30", "-"],
            ["IRS 105", "History of Nigeria", "2", "C", "30", "-"],
            ["PU-IRS 101", "Introduction to International Relations and Diplomacy", "2", "C", "30", "-"],
        ],
        "total_units": "24"
    },
    {
        "level": "100 LEVEL",
        "semester": "SECOND SEMESTER",
        "courses": [
            ["GST 102", "Communication skills in English II", "2", "C", "15", "45"],
            ["GST 104", "Nigeria Peoples and culture", "2", "C", "30", "-"],
            ["PU-GST 114", "Basic Igbo Language and Culture II", "1", "C", "15", "-"],
            ["COS 102", "Problem Solving", "2", "C", "30", "-"],
            ["PU-GST 112", "Leadership, Ethics and Development II", "1", "C", "15", "-"],
            ["PU-MAC 102", "Introduction to Mass Comm.", "2", "C", "30", "-"],
            ["POL 102", "Introduction to Political Science II", "2", "C", "30", "-"],
            ["LAW 112", "Nigeria Legal System II", "1", "C", "15", "-"],
            ["PU-IRS 102", "Introduction to International Relations & Diplomacy II", "2", "C", "30", "-"],
            ["IRS 104", "Rise of Nation States", "2", "C", "30", "-"],
            ["IRS 106", "Evolution of the Contemporary International System", "2", "C", "30", "-"],
        ],
        "total_units": "19"
    },
    {
        "level": "200 LEVEL",
        "semester": "FIRST SEMESTER",
        "courses": [
            ["GST 211", "Entrepreneurship and Innovation", "2", "C", "30", "-"],
            ["IRS 203", "Introduction to Political Analysis", "2", "C", "30", "-"],
            ["IRS 205", "Political Thought since Hobbes", "2", "C", "30", "-"],
            ["IRS 207", "New States in World Politics", "2", "C", "30", "-"],
            ["IRS 209", "Development and Practice of Diplomacy", "2", "C", "30", "-"],
            ["PU-PAD 201", "Introduction to Public Administration I", "2", "C", "30", "-"],
            ["SOC 201", "Introduction to Sociology I", "2", "C", "30", "-"],
            ["PU-GST 213", "Essentials in Igbo Religion and Culture", "1", "C", "15", "-"],
            ["PU-FRE 201", "French", "2", "C", "30", "-"],
            ["IRS 211", "European Politics and Diplomacy 1789 - 1871", "2", "C", "30", "-"],
            ["IRS 213", "Media and International Relations", "2", "C", "30", "-"],
        ],
        "total_units": "21"
    },
    {
        "level": "200 LEVEL",
        "semester": "SECOND SEMESTER",
        "courses": [
            ["GST 212", "Peace and Conflict Resolution", "2", "C", "30", "-"],
            ["IRS 202", "Structures of International Society", "2", "C", "30", "-"],
            ["IRS 204", "Political Thoughts: Plato-Machiavelli", "2", "C", "30", "-"],
            ["IRS 206", "Foundation of Political Economy", "2", "C", "30", "-"],
            ["IRS 210", "Development and Practice of Diplomacy", "2", "C", "30", "-"],
            ["PU-PAD 202", "Introduction to Public Administration II", "2", "C", "30", "-"],
            ["PU-SOC 202", "Introduction to Sociology II", "2", "C", "30", "-"],
            ["CSC 112", "Introduction to Computer and it's Application", "3", "C", "30", "-"],
            ["PU-GST 214", "Cooperative Collegial Democracy", "1", "C", "15", "-"],
            ["PU-FRE 202", "French", "2", "C", "30", "-"],
            ["IRS 212", "European Politics and Diplomacy II", "2", "C", "30", "-"],
        ],
        "total_units": "22"
    },
    {
        "level": "300 LEVEL",
        "semester": "FIRST SEMESTER",
        "courses": [
            ["GST 311", "Start-ups and Venture Creation", "2", "C", "30", "-"],
            ["IRS 301", "International Economic Relations", "2", "C", "30", "-"],
            ["IRS 303", "The International Political System", "2", "C", "30", "-"],
            ["IRS 305", "Law of Nations (International Law)", "2", "C", "30", "-"],
            ["IRS 307", "International Politics in the Post-cold War Era", "2", "C", "30", "-"],
            ["IRS 311", "Theories and Practice of Administration", "2", "C", "30", "-"],
            ["PU-POL 301", "Public Policy and Analysis", "2", "C", "30", "-"],
            ["SSC 301", "Innovation in the Social Science", "2", "C", "30", "-"],
            ["PU-SCC 311", "Social Science Statistics I", "2", "C", "30", "-"],
        ],
        "total_units": "18"
    },
    {
        "level": "300 LEVEL",
        "semester": "SECOND SEMESTER",
        "courses": [
            ["IRS 304", "Diplomacy", "2", "C", "30", "-"],
            ["IRS 306", "Logic and Methods of Political Enquiry", "2", "C", "30", "-"],
            ["IRS 308", "International Politics of Africa", "2", "C", "30", "-"],
            ["IRS 310", "Theories of International Relations", "2", "C", "30", "-"],
            ["IRS 312", "Integration Theories and Regionalism", "2", "C", "30", "-"],
            ["PU-IRS 314", "War & Peace in the 20th Century", "2", "C", "30", "-"],
            ["SSC 302", "Research Methodology I", "2", "C", "30", "-"],
            ["PU-SCC 302", "Social Science Statistics II", "2", "C", "30", "-"],
        ],
        "total_units": "16"
    },
    {
        "level": "400 LEVEL",
        "semester": "FIRST SEMESTER",
        "courses": [
            ["IRS 401", "Foreign Policy Analysis", "4", "C", "45", "-"],
            ["IRS 403", "Human Rights", "3", "C", "45", "-"],
            ["IRS 405", "Foreign Policies of Great Powers", "2", "C", "30", "-"],
            ["IRS 407", "Seminar", "3", "C", "45", "-"],
            ["PU-IRS 409", "International Relations Since 1919", "2", "C", "30", "-"],
            ["IRS 411", "Revolution in History", "2", "C", "30", "-"],
            ["SSC 401", "Research Method II", "2", "C", "30", "-"],
        ],
        "total_units": "18"
    },
    {
        "level": "400 LEVEL",
        "semester": "SECOND SEMESTER",
        "courses": [
            ["IRS 402", "Nigeria Foreign Policies", "2", "C", "30", "-"],
            ["IRS 404", "Contemporary Strategic Studies", "3", "C", "45", "-"],
            ["IRS 406", "International Institutions", "2", "C", "30", "-"],
            ["IRS 492", "Research Project", "6", "C", "45", "-"],
            ["IRS 410", "Military in African Politics", "2", "C", "30", "-"],
            ["PU-IRS 412", "African Political Thoughts", "2", "C", "30", "-"],
        ],
        "total_units": "17"
    },
]

# Calculate total units for the entire programme
TOTAL_PROGRAMME_UNITS = sum(int(sem['total_units']) for sem in COURSE_DATA)
TOTAL_COURSES = sum(len(sem['courses']) for sem in COURSE_DATA)


# -----------------------------------------------------------------------------
# PAGE FOOTER CALLBACK FUNCTION
# -----------------------------------------------------------------------------
def add_footer(canvas, doc):
    """
    Draws the Course Name (bottom left) and Page Number (bottom right) on each page.
    """
    page_num = canvas.getPageNumber()
    
    canvas.saveState()
    canvas.setFont('Helvetica', 8)
    canvas.setFillColor(HexColor('#64748B'))  # Subtle grey color
    
    # Bottom Left: Programme Name
    canvas.drawString(15*mm, 10*mm, f"{PROGRAMME_NAME}")
    
    # Bottom Right: Page Number
    canvas.drawRightString(A4[0] - 15*mm, 10*mm, f"Page {page_num}")
    
    canvas.restoreState()


# -----------------------------------------------------------------------------
# TABLE HEADER AND STYLING FUNCTION
# -----------------------------------------------------------------------------
def create_course_table(sem_data, semester_display):
    """
    Creates a formatted table for a semester's courses
    """
    # Table Header
    table_data = [["CODE", "COURSE TITLE", "UNIT(S)", "STATUS", "LH", "PH"]]
    
    # Add Courses
    for course in sem_data['courses']:
        course_code = course[0]
        course_title = course[1]
        units = course[2]
        status = course[3]
        lh = course[4] if course[4] != "-" else "-"
        ph = course[5] if course[5] != "-" else "-"
        table_data.append([course_code, course_title, units, status, lh, ph])
    
    # Add Total Units Row
    table_data.append(["", "TOTAL", sem_data['total_units'], "", "", ""])
    
    # Set column widths
    col_widths = [32*mm, 78*mm, 15*mm, 18*mm, 15*mm, 15*mm]
    
    # Create table
    t = Table(table_data, colWidths=col_widths, repeatRows=1)
    
    # Apply styles
    puni_navy = HexColor('#0A192F')
    puni_gold = HexColor('#F5A623')
    light_bg = HexColor('#F8FAFC')
    
    t.setStyle(TableStyle([
        # Header Styling
        ('BACKGROUND', (0, 0), (-1, 0), puni_navy),
        ('TEXTCOLOR', (0, 0), (-1, 0), white),
        ('FONTNAME', (0, 0), (-1, 0), 'Helvetica-Bold'),
        ('FONTSIZE', (0, 0), (-1, 0), 9),
        ('ALIGN', (0, 0), (-1, 0), 'CENTER'),
        ('BOTTOMPADDING', (0, 0), (-1, 0), 8),
        ('TOPPADDING', (0, 0), (-1, 0), 8),
        
        # Body Styling
        ('FONTNAME', (0, 1), (-1, -2), 'Helvetica'),
        ('FONTSIZE', (0, 1), (-1, -2), 8.5),
        ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
        ('GRID', (0, 0), (-1, -2), 0.5, lightgrey),
        
        # Center align specific columns
        ('ALIGN', (2, 1), (2, -2), 'CENTER'),  # UNIT(S)
        ('ALIGN', (3, 1), (3, -2), 'CENTER'),  # STATUS
        ('ALIGN', (4, 1), (4, -2), 'CENTER'),  # LH
        ('ALIGN', (5, 1), (5, -2), 'CENTER'),  # PH
        
        # Total Units Row Styling
        ('FONTNAME', (0, -1), (-1, -1), 'Helvetica-Bold'),
        ('FONTSIZE', (0, -1), (-1, -1), 9.5),
        ('TEXTCOLOR', (0, -1), (-1, -1), puni_navy),
        ('BACKGROUND', (0, -1), (-1, -1), light_bg),
        ('ALIGN', (1, -1), (1, -1), 'RIGHT'),
        ('LINEABOVE', (0, -1), (-1, -1), 1, puni_gold),
        ('LINEBELOW', (0, -1), (-1, -1), 1, puni_gold),
        ('SPAN', (0, -1), (1, -1)),  # Span first two columns for total row
    ]))
    
    return t


# -----------------------------------------------------------------------------
# PDF GENERATION
# -----------------------------------------------------------------------------
def generate_pdf():
    output_file = f"Course_Structure_International_Relations_Diplomacy.pdf"
    
    try:
        doc = SimpleDocTemplate(
            output_file,
            pagesize=A4,
            rightMargin=15*mm, leftMargin=15*mm,
            topMargin=20*mm, bottomMargin=20*mm
        )
        styles = getSampleStyleSheet()
        
        # Peter University Theme Colors
        puni_navy = HexColor('#0A192F')
        puni_gold = HexColor('#F5A623')
        puni_oxblood = HexColor('#76323F')
        dark_gray = HexColor('#334155')
        medium_gray = HexColor('#475569')
        
        # Custom Paragraph Styles
        styles.add(ParagraphStyle(
            name='UniversityTitle', 
            fontName='Helvetica-Bold', 
            fontSize=22, 
            leading=26, 
            alignment=TA_CENTER, 
            spaceAfter=6,
            textColor=puni_navy
        ))
        styles.add(ParagraphStyle(
            name='FacultyTitle', 
            fontName='Helvetica-Bold', 
            fontSize=13, 
            leading=16, 
            alignment=TA_CENTER, 
            spaceAfter=10,
            textColor=dark_gray
        ))
        styles.add(ParagraphStyle(
            name='ProgrammeTitle', 
            fontName='Helvetica-Bold', 
            fontSize=16, 
            leading=20, 
            alignment=TA_CENTER, 
            spaceAfter=5,
            textColor=puni_oxblood
        ))
        styles.add(ParagraphStyle(
            name='DocSubtitle', 
            fontName='Helvetica', 
            fontSize=11, 
            leading=14, 
            alignment=TA_CENTER, 
            spaceAfter=20,
            textColor=medium_gray
        ))
        styles.add(ParagraphStyle(
            name='LevelHeader', 
            fontName='Helvetica-Bold', 
            fontSize=14, 
            leading=18, 
            alignment=TA_LEFT, 
            spaceBefore=25,
            spaceAfter=8,
            textColor=puni_navy,
            keepWithNext=True
        ))
        styles.add(ParagraphStyle(
            name='SemesterHeader', 
            fontName='Helvetica-Bold', 
            fontSize=12, 
            leading=15, 
            alignment=TA_LEFT, 
            spaceBefore=8,
            spaceAfter=8,
            textColor=puni_oxblood,
            keepWithNext=True
        ))
        styles.add(ParagraphStyle(
            name='InfoText', 
            fontName='Helvetica', 
            fontSize=9, 
            leading=12, 
            alignment=TA_CENTER,
            spaceAfter=15,
            textColor=medium_gray
        ))
        styles.add(ParagraphStyle(
            name='SummaryTitle', 
            fontName='Helvetica-Bold', 
            fontSize=12, 
            leading=16, 
            alignment=TA_LEFT,
            spaceBefore=20,
            spaceAfter=10,
            textColor=puni_navy
        ))

        story = []
        
        # ========== COVER / DOCUMENT HEADER ==========
        story.append(Paragraph(UNIVERSITY_NAME, styles['UniversityTitle']))
        story.append(Paragraph(FACULTY_NAME, styles['FacultyTitle']))
        story.append(Paragraph(PROGRAMME_NAME, styles['ProgrammeTitle']))
        story.append(Paragraph("Four Years B.Sc Degree Programme (Regular)", styles['DocSubtitle']))
        
        # Add a decorative line
        story.append(Spacer(1, 5))
        
        # ========== PROGRAMME SUMMARY ==========
        summary_text = f"""
        The B.Sc. programme in {PROGRAMME_NAME} is a four-year degree programme 
        designed to equip students with comprehensive knowledge and skills in 
        international relations, diplomacy, political analysis, and global affairs. 
        The programme comprises a total of <b>{TOTAL_PROGRAMME_UNITS} units</b> across 
        <b>{TOTAL_COURSES} courses</b>, structured across eight semesters.
        """
        story.append(Paragraph(summary_text, styles['InfoText']))
        
        # ========== COURSE STRUCTURE TABLES ==========
        current_level = None
        
        for sem_data in COURSE_DATA:
            level = sem_data['level']
            semester = sem_data['semester']
            semester_display = f"{level} - {semester}"
            
            # Add Level header when level changes
            if current_level != level:
                story.append(Paragraph(level, styles['LevelHeader']))
                current_level = level
            
            # Add Semester header
            story.append(Paragraph(semester, styles['SemesterHeader']))
            
            # Create and add table
            table = create_course_table(sem_data, semester_display)
            story.append(table)
            story.append(Spacer(1, 8))
        
        # ========== SUMMARY SECTION ==========
        story.append(PageBreak())
        
        # Programme Summary Header
        story.append(Paragraph("PROGRAMME SUMMARY", styles['LevelHeader']))
        story.append(Spacer(1, 10))
        
        # Create summary table
        summary_data = [
            ["S/N", "LEVEL", "SEMESTER", "UNITS", "COURSES"],
        ]
        
        sn = 1
        for sem_data in COURSE_DATA:
            summary_data.append([
                str(sn),
                sem_data['level'],
                sem_data['semester'],
                sem_data['total_units'],
                str(len(sem_data['courses']))
            ])
            sn += 1
        
        # Add Total row
        summary_data.append(["", "", "TOTAL", str(TOTAL_PROGRAMME_UNITS), str(TOTAL_COURSES)])
        
        # Create summary table
        col_widths = [20*mm, 35*mm, 60*mm, 25*mm, 25*mm]
        summary_table = Table(summary_data, colWidths=col_widths, repeatRows=1)
        
        puni_navy = HexColor('#0A192F')
        puni_oxblood = HexColor('#76323F')
        light_bg = HexColor('#F8FAFC')
        
        summary_table.setStyle(TableStyle([
            # Header
            ('BACKGROUND', (0, 0), (-1, 0), puni_navy),
            ('TEXTCOLOR', (0, 0), (-1, 0), white),
            ('FONTNAME', (0, 0), (-1, 0), 'Helvetica-Bold'),
            ('FONTSIZE', (0, 0), (-1, 0), 10),
            ('ALIGN', (0, 0), (-1, 0), 'CENTER'),
            ('BOTTOMPADDING', (0, 0), (-1, 0), 8),
            ('TOPPADDING', (0, 0), (-1, 0), 8),
            
            # Body
            ('FONTNAME', (0, 1), (-1, -2), 'Helvetica'),
            ('FONTSIZE', (0, 1), (-1, -2), 9),
            ('GRID', (0, 0), (-1, -2), 0.5, lightgrey),
            ('ALIGN', (0, 1), (0, -2), 'CENTER'),  # S/N
            ('ALIGN', (3, 1), (3, -2), 'CENTER'),  # Units
            ('ALIGN', (4, 1), (4, -2), 'CENTER'),  # Courses
            
            # Total row
            ('FONTNAME', (0, -1), (-1, -1), 'Helvetica-Bold'),
            ('FONTSIZE', (0, -1), (-1, -1), 10),
            ('TEXTCOLOR', (0, -1), (-1, -1), puni_oxblood),
            ('BACKGROUND', (0, -1), (-1, -1), light_bg),
            ('LINEABOVE', (0, -1), (-1, -1), 1, puni_navy),
            ('SPAN', (0, -1), (1, -1)),  # Span first two columns
            ('ALIGN', (2, -1), (2, -1), 'RIGHT'),
        ]))
        
        story.append(summary_table)
        
        # ========== NOTES SECTION ==========
        story.append(Spacer(1, 20))
        story.append(Paragraph("NOTES:", styles['SummaryTitle']))
        story.append(Spacer(1, 5))
        
        notes = [
            "C = Compulsory / Core Course",
            "LH = Lecture Hours per Semester",
            "PH = Practical Hours per Semester",
            "Total Programme Units: 155 units over 4 years",
            "",
            "For more information, please contact:",
            "Department of International Relations & Diplomacy",
            "Faculty of Arts, Management & Social Sciences",
            "Peter University, Achina/Onneh, Anambra State, Nigeria"
        ]
        
        for note in notes:
            if note == "":
                story.append(Spacer(1, 5))
            else:
                story.append(Paragraph(f"• {note}", styles['InfoText']))
        
        # Build document
        doc.build(story, onFirstPage=add_footer, onLaterPages=add_footer)
        print(f"✅ Course Structure PDF successfully generated: {output_file}")
        print(f"   Programme: {PROGRAMME_NAME}")
        print(f"   Total Units: {TOTAL_PROGRAMME_UNITS}")
        print(f"   Total Courses: {TOTAL_COURSES}")
        return True
        
    except Exception as e:
        print(f"❌ Error generating PDF: {str(e)}")
        import traceback
        traceback.print_exc()
        return False


if __name__ == "__main__":
    generate_pdf()