from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from io import BytesIO
from fastapi.responses import StreamingResponse
from reportlab.lib.pagesizes import A4
from reportlab.platypus import SimpleDocTemplate, Table, TableStyle, Paragraph, Spacer
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib import colors

from app.database.main.mysql import get_db
from app.dependency.authantication import JWTPayloadSchema, get_current_student
from app.api.module_9_report.service import Module9ReportService
from app.api.module_9_report.schema import Module9ReportPreview

module_9_report_router = APIRouter()


@module_9_report_router.get("/preview9/{group_id}", response_model=Module9ReportPreview)
async def get_module9_report_preview(
    group_id: int,
    db: Session = Depends(get_db),
    token: JWTPayloadSchema = Depends(get_current_student)
):
    """Preview Module 9 report data"""
    try:
        service = Module9ReportService(db, token)
        return await service.get_report_preview(group_id)
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@module_9_report_router.get("/{group_id}/preview-report-pdf9")
async def preview_report_pdf(
    group_id: int,
    db: Session = Depends(get_db),
    token: JWTPayloadSchema = Depends(get_current_student)
):
    """Generate and save PDF report"""
    try:
        service = Module9ReportService(db, token)
        file_path = await service.generate_and_save_pdf(group_id)
        return {"group_id": group_id, "file_path": file_path}
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@module_9_report_router.get("/download9/{group_id}")
async def download_module9_report(
    group_id: int,
    db: Session = Depends(get_db),
    token: JWTPayloadSchema = Depends(get_current_student)
):
    """Download Module 9 report as PDF"""
    try:
        service = Module9ReportService(db, token)
        report = await service._fetch_module9_data(group_id)

        buffer = BytesIO()
        doc = SimpleDocTemplate(buffer, pagesize=A4,
                                leftMargin=30, rightMargin=30,
                                topMargin=50, bottomMargin=50)
        styles = getSampleStyleSheet()
        story = []

        # Title
        title_style = ParagraphStyle(
            'CustomTitle', parent=styles['Heading1'],
            fontSize=16, spaceAfter=20,
            alignment=1, fontName='Helvetica-Bold')
        
        # Section style
        section_style = ParagraphStyle(
            'SectionHeader', parent=styles['Heading2'],
            fontSize=12, spaceAfter=10,
            fontName='Helvetica-Bold')
        
        story.append(Paragraph("Module 9: Backend & Supply Chain", title_style))
        story.append(Paragraph("Adapting Supply Chain Analysis", styles['Italic']))
        story.append(Spacer(1, 20))

        # Supply Chain Adaptation Entries
        story.append(Paragraph("Supply Chain Adaptation Entries", section_style))
        
        adaptation_data = [['Entry ID', 'Categories', 'Remarks', 'Adaptation Needed', 'Point & Rationale']]
        for item in report.supply_chain_adaptation:
            adaptation_data.append([
                str(item.adapting_id or ''),
                item.what_are_some_categories or 'N/A',
                item.remarks_about_these_categories or 'N/A',
                item.do_you_think_you_need or 'N/A',
                item.at_which_point_and_why or 'N/A'
            ])
        
        if len(adaptation_data) == 1:  # Only headers
            adaptation_data.append(['N/A', 'N/A', 'N/A', 'N/A', 'N/A'])
        
        # Calculate row heights - header gets 30, data rows get minimum 40
        row_heights = [30]  # Header row
        for i in range(1, len(adaptation_data)):
            row_heights.append(40)  # Minimum height for data rows
        
        adaptation_table = Table(adaptation_data, colWidths=[50, 120, 150, 100, 150], rowHeights=row_heights)
        adaptation_table.setStyle(TableStyle([
            ('GRID', (0, 0), (-1, -1), 1, colors.black),
            ('FONTNAME', (0, 0), (-1, 0), 'Helvetica-Bold'),
            ('FONTNAME', (0, 1), (-1, -1), 'Helvetica'),
            ('FONTSIZE', (0, 0), (-1, -1), 8),
            ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
            ('VALIGN', (0, 0), (-1, -1), 'TOP'),
            ('TOPPADDING', (0, 0), (-1, -1), 8),
            ('BOTTOMPADDING', (0, 0), (-1, -1), 8),
            ('LEFTPADDING', (0, 0), (-1, -1), 4),
            ('RIGHTPADDING', (0, 0), (-1, -1), 4)
        ]))
        story.append(adaptation_table)
        story.append(Spacer(1, 15))

        # Summary Statistics
        story.append(Paragraph("Summary Statistics", section_style))
        
        total_entries = len(report.supply_chain_adaptation) if report.supply_chain_adaptation else 0
        requiring_adaptation = sum(1 for item in report.supply_chain_adaptation 
                                 if item.do_you_think_you_need and item.do_you_think_you_need.lower() == 'yes') if report.supply_chain_adaptation else 0
        not_requiring_adaptation = total_entries - requiring_adaptation
        
        summary_data = [
            ['Total Entries', str(total_entries)],
            ['Categories Requiring Adaptation', str(requiring_adaptation)],
            ['Categories Not Requiring Adaptation', str(not_requiring_adaptation)]
        ]
        
        summary_table = Table(summary_data, colWidths=[200, 100])
        summary_table.setStyle(TableStyle([
            ('GRID', (0, 0), (-1, -1), 1, colors.black),
            ('FONTNAME', (0, 0), (-1, -1), 'Helvetica'),
            ('FONTSIZE', (0, 0), (-1, -1), 10),
            ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
            ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
            ('TOPPADDING', (0, 0), (-1, -1), 6),
            ('BOTTOMPADDING', (0, 0), (-1, -1), 6)
        ]))
        story.append(summary_table)
        story.append(Spacer(1, 15))

        # Analysis Summary
        story.append(Paragraph("Analysis Summary", section_style))
        
        # Get summary data from database
        additional_remarks = "N/A"
        key_takeaways = "N/A"
        
        if report.summary:
            additional_remarks = report.summary.backend_submissions or "N/A"
            key_takeaways = report.summary.backend_summarise or "N/A"
        
        analysis_data = [
            ['Additional Remarks', additional_remarks],
            ['Key Takeaways', key_takeaways]
        ]
        
        analysis_table = Table(analysis_data, colWidths=[120, 360], rowHeights=None)
        analysis_table.setStyle(TableStyle([
            ('GRID', (0, 0), (-1, -1), 1, colors.black),
            ('FONTNAME', (0, 0), (-1, 0), 'Helvetica-Bold'),
            ('FONTNAME', (0, 1), (-1, -1), 'Helvetica'),
            ('FONTSIZE', (0, 0), (-1, -1), 9),
            ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
            ('VALIGN', (0, 0), (-1, -1), 'TOP'),
            ('TOPPADDING', (0, 0), (-1, -1), 8),
            ('BOTTOMPADDING', (0, 0), (-1, -1), 8),
            ('WORDWRAP', (0, 0), (-1, -1), True)
        ]))
        story.append(analysis_table)
        story.append(Spacer(1, 20))



        doc.build(story)
        buffer.seek(0)

        return StreamingResponse(
            BytesIO(buffer.read()),
            media_type="application/pdf",
            headers={"Content-Disposition": f"attachment; filename=module_9_report_group_{group_id}.pdf"}
        )

    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))