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, Image
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')
        
        # Logo
        try:
            logo = Image("TS Logo.png", width=150, height=75)
            logo.hAlign = 'LEFT'
            story.append(logo)
            story.append(Spacer(1, 10))
        except:
            pass  # Continue without logo if file not found
        
        story.append(Paragraph("Module 9: Backend & Supply Chain", title_style))
        story.append(Spacer(1, 20))

        # Create flexible paragraph style for table content
        flexible_style = ParagraphStyle(
            'FlexibleStyle', parent=styles['Normal'],
            fontSize=9, leading=11, wordWrap='CJK'
        )
        
        # Supply Chain Adaptation Entries
        story.append(Paragraph("Supply Chain Adaptation Entries", section_style))
        
        adaptation_data = [[
            Paragraph('Entry ID', flexible_style),
            Paragraph('Categories', flexible_style),
            Paragraph('Remarks', flexible_style),
            Paragraph('Adaptation Needed', flexible_style),
            Paragraph('Point & Rationale', flexible_style)
        ]]
        for item in report.supply_chain_adaptation:
            adaptation_data.append([
                Paragraph(str(item.adapting_id or 'N/A'), flexible_style),
                Paragraph(item.what_are_some_categories or 'N/A', flexible_style),
                Paragraph(item.remarks_about_these_categories or 'N/A', flexible_style),
                Paragraph(item.do_you_think_you_need or 'N/A', flexible_style),
                Paragraph(item.at_which_point_and_why or 'N/A', flexible_style)
            ])
        
        if len(adaptation_data) == 1:  # Only headers
            adaptation_data.append([
                Paragraph('N/A', flexible_style),
                Paragraph('N/A', flexible_style),
                Paragraph('N/A', flexible_style),
                Paragraph('N/A', flexible_style),
                Paragraph('N/A', flexible_style)
            ])
        
        adaptation_table = Table(adaptation_data, colWidths=[50, 120, 150, 100, 150])
        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 = [
            [Paragraph('Total Entries', flexible_style), Paragraph(str(total_entries), flexible_style)],
            [Paragraph('Categories Requiring Adaptation', flexible_style), Paragraph(str(requiring_adaptation), flexible_style)],
            [Paragraph('Categories Not Requiring Adaptation', flexible_style), Paragraph(str(not_requiring_adaptation), flexible_style)]
        ]
        
        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 = [
            [Paragraph('Additional Remarks', flexible_style), Paragraph(additional_remarks, flexible_style)],
            [Paragraph('Key Takeaways', flexible_style), Paragraph(key_takeaways, flexible_style)]
        ]
        
        analysis_table = Table(analysis_data, colWidths=[120, 360])
        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))