from fastapi import APIRouter, Depends, Response ,HTTPException
from fastapi.responses import FileResponse
from sqlalchemy.orm import Session
from io import BytesIO
import os
from reportlab.lib.pagesizes import A4
from reportlab.lib import colors
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle, Image
from app.api.module_1.schema import Module1ReportPreview
from app.api.module_1.service import Module1ReportService
from app.database.main.mysql import get_db
from app.dependency.authantication import JWTPayloadSchema, get_current_student
from app.models.main.summary import TblSummary
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.units import inch


module_1_report_router = APIRouter()


@module_1_report_router.get("/{group_id}/preview1", response_model=Module1ReportPreview)
async def preview_report(
    group_id: int,
    db: Session = Depends(get_db),
    token: JWTPayloadSchema = Depends(get_current_student)
):
    try:
        service = Module1ReportService(db,token)
        return service._fetch_module1_data(group_id)
    except HTTPException:
        raise  # Keep same behavior for FastAPI HTTPExceptions
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Error: {str(e)}")


@module_1_report_router.get("/{group_id}/download1")
async def download_report(
    group_id: int,
    db: Session = Depends(get_db),
    token: JWTPayloadSchema = Depends(get_current_student)
):
    service = Module1ReportService(db,token)
    report = service._fetch_module1_data(group_id)
    
    # Calculate capital expense sums for Store Format A
    format_a_civil = sum([item.total or 0 for item in report.civil if 'A' in str(item.store_format_type)])
    format_a_display = sum([item.total or 0 for item in report.display_racking_units if 'A' in str(item.store_format_type)])
    format_a_carpentry = sum([item.total or 0 for item in report.carpentry if 'A' in str(item.store_format_type)])
    format_a_electrical = sum([item.total or 0 for item in report.electrical_cabling if 'A' in str(item.store_format_type)])
    format_a_equipment = sum([item.total or 0 for item in report.commercial_equipment if 'A' in str(item.store_format_type)])
    format_a_signage = sum([item.total or 0 for item in report.display_boards if 'A' in str(item.store_format_type)])
    format_a_it = sum([item.total or 0 for item in report.infotech if 'A' in str(item.store_format_type)])
    format_a_visual = sum([item.total or 0 for item in report.visual_merchandising])
    format_a_plumbing = sum([item.total or 0 for item in report.plumbing])
    format_a_others = sum([item.total_cost or 0 for item in report.additional_installations])
    format_a_total = (
        format_a_civil + format_a_display + format_a_carpentry + format_a_electrical +
        format_a_equipment + format_a_signage + format_a_it + format_a_visual +
        format_a_plumbing + format_a_others
    )
    
    # Calculate capital expense sums for Store Format B
    format_b_civil = sum([item.total or 0 for item in report.civil if 'B' in str(item.store_format_type)])
    format_b_display = sum([item.total or 0 for item in report.display_racking_units if 'B' in str(item.store_format_type)])
    format_b_carpentry = sum([item.total or 0 for item in report.carpentry if 'B' in str(item.store_format_type)])
    format_b_electrical = sum([item.total or 0 for item in report.electrical_cabling if 'B' in str(item.store_format_type)])
    format_b_equipment = sum([item.total or 0 for item in report.commercial_equipment if 'B' in str(item.store_format_type)])
    format_b_signage = sum([item.total or 0 for item in report.display_boards if 'B' in str(item.store_format_type)])
    format_b_it = sum([item.total or 0 for item in report.infotech if 'B' in str(item.store_format_type)])
    format_b_visual = format_a_visual  # assuming visual merchandising same as A
    format_b_plumbing = format_a_plumbing  # assuming plumbing same as A
    format_b_others = format_a_others  # assuming other same as A
    format_b_total = (
        format_b_civil + format_b_display + format_b_carpentry + format_b_electrical +
        format_b_equipment + format_b_signage + format_b_it + format_b_visual +
        format_b_plumbing + format_b_others
    )
    
    buffer = BytesIO()
    doc = SimpleDocTemplate(buffer, pagesize=A4, leftMargin=50, rightMargin=50, topMargin=50, bottomMargin=50)
    styles = getSampleStyleSheet()
    story = []
    
    # 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
    
    # Title style
    title_style = ParagraphStyle(
        'CustomTitle',
        parent=styles['Heading1'],
        fontSize=16,
        spaceAfter=20,
        alignment=1,
        fontName='Helvetica-Bold'
    )
    story.append(Paragraph("Module 1: Store Format & Details", title_style))
    story.append(Spacer(1, 10))
    
    # Section header style
    section_style = ParagraphStyle(
        'SectionHeader',
        parent=styles['Heading2'],
        fontSize=14,
        spaceAfter=10,
        fontName='Helvetica-Bold'
    )
    
    # Branding & Store Details
    story.append(Paragraph("Branding & Store Details", section_style))
    story.append(Spacer(1, 8))
    story.append(Paragraph(f"<b>Name of the Store:</b> {report.brand.brand_name or 'N/A'}", styles['Normal']))
    story.append(Paragraph(f"<b>Rationale:</b> {report.brand.rationale or 'N/A'}", styles['Normal']))
    story.append(Spacer(1, 12))
    
    # Consumer Segments & Catchment Sizes
    story.append(Paragraph("Consumer Segments & Catchment Sizes", section_style))
    story.append(Spacer(1, 15))
    for i, segment in enumerate(report.segments, 1):
        # Display all segments, even if segment_name is "N/A"
        segment_name = segment.segment_name if segment.segment_name and segment.segment_name != "N/A" else f"Segment {i}"
        story.append(Paragraph(f"<b>Segment {i}: {segment_name}</b>", styles['Normal']))
        story.append(Spacer(1, 6))
        story.append(Paragraph(f"<b>ISEC Segmentation:</b> {segment.isec_value or 0}", styles['Normal']))
        story.append(Spacer(1, 4))
        story.append(Paragraph(f"• <b>Chief Wage Earner's Occupation:</b> {segment.chief_wage_earner_occupation if segment.chief_wage_earner_occupation != 'N/A' else 'Not specified'}", styles['Normal']))
        story.append(Spacer(1, 3))
        story.append(Paragraph(f"• <b>Education of the highest educated male adult:</b> {segment.male_education if segment.male_education != 'N/A' else 'Not specified'}", styles['Normal']))
        story.append(Spacer(1, 3))
        story.append(Paragraph(f"• <b>Education of the highest educated female adult:</b> {segment.female_education if segment.female_education != 'N/A' else 'Not specified'}", styles['Normal']))
        story.append(Spacer(1, 3))
        story.append(Paragraph(f"• <b>Location:</b> {segment.location if segment.location != 'N/A' else 'Not specified'}", styles['Normal']))
        story.append(Spacer(1, 3))
        story.append(Paragraph(f"• <b>Catchment Size:</b> {segment.total_population or 'Not specified'}", styles['Normal']))
        story.append(Spacer(1, 18))
    
    # Store Format Details
    story.append(Paragraph("Store Format Details", section_style))
    story.append(Spacer(1, 15))
    
    # Store Format A
    if len(report.store_formats) > 0 and report.store_formats[0].store_name != "N/A":
        sf_a = report.store_formats[0]
        story.append(Paragraph(f"<b>Store Format A: {sf_a.store_name}</b>", styles['Normal']))
        story.append(Spacer(1, 6))
        story.append(Paragraph(f"• <b>Store Size (in sq. ft.):</b> {sf_a.store_size or 0.0}", styles['Normal']))
        story.append(Spacer(1, 3))
        story.append(Paragraph(f"• <b>Merchandise:</b> {sf_a.merchandise or 'Not Set'}", styles['Normal']))
        story.append(Spacer(1, 3))
        story.append(Paragraph(f"• <b>Merchandise Rationale:</b> {getattr(sf_a, 'merchandise_rationale', 'Not provided')}", styles['Normal']))
        story.append(Spacer(1, 3))
        story.append(Paragraph(f"• <b>Pricing Strategy:</b> {getattr(sf_a, 'pricing_strategy', 'Not Set')}", styles['Normal']))
        story.append(Spacer(1, 3))
        story.append(Paragraph(f"• <b>Location:</b> {sf_a.location or 'Not Set'}", styles['Normal']))
        story.append(Spacer(1, 3))
        story.append(Paragraph(f"• <b>Service Parameters:</b> {sf_a.service_parameters or 'Not Set'}", styles['Normal']))
        story.append(Spacer(1, 3))
        story.append(Paragraph(f"• <b>Technology Adoption:</b> {sf_a.technology_adoption or 'Not Set'}", styles['Normal']))
        story.append(Spacer(1, 3))
        story.append(Paragraph(f"• <b>Other Parameters:</b> {sf_a.other_parameters or 'Not Set'}", styles['Normal']))

    else:
        story.append(Paragraph("<b>Store Format A: Not Set</b>", styles['Normal']))
        story.append(Spacer(1, 6))
        story.append(Paragraph("• <b>Store Size (in sq. ft.):</b> 0.0", styles['Normal']))
        story.append(Spacer(1, 3))
        story.append(Paragraph("• <b>Merchandise:</b> Not Set", styles['Normal']))
        story.append(Spacer(1, 3))
        story.append(Paragraph("• <b>Merchandise Rationale:</b> Not provided", styles['Normal']))
        story.append(Spacer(1, 3))
        story.append(Paragraph("• <b>Pricing Strategy:</b> Not Set", styles['Normal']))
        story.append(Spacer(1, 3))
        story.append(Paragraph("• <b>Location:</b> Not Set", styles['Normal']))
        story.append(Spacer(1, 3))
        story.append(Paragraph("• <b>Service Parameters:</b> Not Set", styles['Normal']))
        story.append(Spacer(1, 3))
        story.append(Paragraph("• <b>Technology Adoption:</b> Not Set", styles['Normal']))
        story.append(Spacer(1, 3))
        story.append(Paragraph("• <b>Other Parameters:</b> Not Set", styles['Normal']))
    story.append(Spacer(1, 20))
    
    # Store Format B - Start on new page
   # from reportlab.platypus import PageBreak
   # story.append(PageBreak())
    
    if len(report.store_formats) > 1 and report.store_formats[1].store_name != "N/A":
        sf_b = report.store_formats[1]
        story.append(Paragraph(f"<b>Store Format B: {sf_b.store_name}</b>", styles['Normal']))
        story.append(Spacer(1, 6))
        story.append(Paragraph(f"• <b>Store Size (in sq. ft.):</b> {sf_b.store_size or 0.0}", styles['Normal']))
        story.append(Spacer(1, 3))
        story.append(Paragraph(f"• <b>Merchandise:</b> {sf_b.merchandise or 'Not Set'}", styles['Normal']))
        story.append(Spacer(1, 3))
        story.append(Paragraph(f"• <b>Merchandise Rationale:</b> {getattr(sf_b, 'merchandise_rationale', 'Not provided')}", styles['Normal']))
        story.append(Spacer(1, 3))
        story.append(Paragraph(f"• <b>Pricing Strategy:</b> {getattr(sf_b, 'pricing_strategy', 'Not Set')}", styles['Normal']))
        story.append(Spacer(1, 3))
        story.append(Paragraph(f"• <b>Location:</b> {sf_b.location or 'Not Set'}", styles['Normal']))
        story.append(Spacer(1, 3))
        story.append(Paragraph(f"• <b>Service Parameters:</b> {sf_b.service_parameters or 'Not Set'}", styles['Normal']))
        story.append(Spacer(1, 3))
        story.append(Paragraph(f"• <b>Technology Adoption:</b> {sf_b.technology_adoption or 'Not Set'}", styles['Normal']))
        story.append(Spacer(1, 3))
        story.append(Paragraph(f"• <b>Other Parameters:</b> {sf_b.other_parameters or 'Not Set'}", styles['Normal']))

    else:
        story.append(Paragraph("<b>Store Format B: Not Set</b>", styles['Normal']))
        story.append(Spacer(1, 6))
        story.append(Paragraph("• <b>Store Size (in sq. ft.):</b> 0.0", styles['Normal']))
        story.append(Spacer(1, 3))
        story.append(Paragraph("• <b>Merchandise:</b> Not Set", styles['Normal']))
        story.append(Spacer(1, 3))
        story.append(Paragraph("• <b>Merchandise Rationale:</b> Not provided", styles['Normal']))
        story.append(Spacer(1, 3))
        story.append(Paragraph("• <b>Pricing Strategy:</b> Not Set", styles['Normal']))
        story.append(Spacer(1, 3))
        story.append(Paragraph("• <b>Location:</b> Not Set", styles['Normal']))
        story.append(Spacer(1, 3))
        story.append(Paragraph("• <b>Service Parameters:</b> Not Set", styles['Normal']))
        story.append(Spacer(1, 3))
        story.append(Paragraph("• <b>Technology Adoption:</b> Not Set", styles['Normal']))
        story.append(Spacer(1, 3))
        story.append(Paragraph("• <b>Other Parameters:</b> Not Set", styles['Normal']))
    story.append(Spacer(1, 20))
    
    # Capital Expenses Section
    story.append(Paragraph("Capital Expenses", section_style))
    story.append(Spacer(1, 10))
    
    # Store Format A Capital Expenses Table
    story.append(Paragraph("<b>Store Format A</b>", styles['Normal']))
    story.append(Spacer(1, 10))
    capex_a_data = [
        [Paragraph('Civil Work', styles['Normal']), Paragraph(f"Rs. {format_a_civil:,.2f}", styles['Normal'])],
        [Paragraph('Racking and Display Units', styles['Normal']), Paragraph(f"Rs. {format_a_display:,.2f}", styles['Normal'])],
        [Paragraph('Carpentry and Furniture', styles['Normal']), Paragraph(f"Rs. {format_a_carpentry:,.2f}", styles['Normal'])],
        [Paragraph('Electrical and Cabling', styles['Normal']), Paragraph(f"Rs. {format_a_electrical:,.2f}", styles['Normal'])],
        [Paragraph('Commercial Equipment', styles['Normal']), Paragraph(f"Rs. {format_a_equipment:,.2f}", styles['Normal'])],
        [Paragraph('Signage and Display Boards', styles['Normal']), Paragraph(f"Rs. {format_a_signage:,.2f}", styles['Normal'])],
        [Paragraph('Information Technology', styles['Normal']), Paragraph(f"Rs. {format_a_it:,.2f}", styles['Normal'])],
        [Paragraph('Visual Merchandising', styles['Normal']), Paragraph(f"Rs. {format_a_visual:,.2f}", styles['Normal'])],
        [Paragraph('Plumbing', styles['Normal']), Paragraph(f"Rs. {format_a_plumbing:,.2f}", styles['Normal'])],
        [Paragraph('Others', styles['Normal']), Paragraph(f"Rs. {format_a_others:,.2f}", styles['Normal'])],
        [Paragraph('<b>Total</b>', styles['Normal']), Paragraph(f"<b>Rs. {format_a_total:,.2f}</b>", styles['Normal'])]
    ]
    capex_a_table = Table(capex_a_data, colWidths=[2.5*inch, 1.5*inch])
    capex_a_table.setStyle(TableStyle([
        ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
        ('VALIGN', (0, 0), (-1, -1), 'TOP'),
        ('BACKGROUND', (0, -1), (-1, -1), colors.lightgrey),
        ('GRID', (0, 0), (-1, -1), 0.5, colors.black),
        ('WORDWRAP', (0, 0), (-1, -1), True),
        ('LEFTPADDING', (0, 0), (-1, -1), 4),
        ('RIGHTPADDING', (0, 0), (-1, -1), 4),
        ('TOPPADDING', (0, 0), (-1, -1), 4),
        ('BOTTOMPADDING', (0, 0), (-1, -1), 4)
    ]))
    story.append(capex_a_table)
    story.append(Spacer(1, 13))
    
    # Store Format B Capital Expenses Table
    story.append(Paragraph("<b>Store Format B</b>", styles['Normal']))
    story.append(Spacer(1, 10))
    capex_b_data = [
        [Paragraph('Civil Work', styles['Normal']), Paragraph(f"Rs. {format_b_civil:,.2f}", styles['Normal'])],
        [Paragraph('Racking and Display Units', styles['Normal']), Paragraph(f"Rs. {format_b_display:,.2f}", styles['Normal'])],
        [Paragraph('Carpentry and Furniture', styles['Normal']), Paragraph(f"Rs. {format_b_carpentry:,.2f}", styles['Normal'])],
        [Paragraph('Electrical and Cabling', styles['Normal']), Paragraph(f"Rs. {format_b_electrical:,.2f}", styles['Normal'])],
        [Paragraph('Commercial Equipment', styles['Normal']), Paragraph(f"Rs. {format_b_equipment:,.2f}", styles['Normal'])],
        [Paragraph('Signage and Display Boards', styles['Normal']), Paragraph(f"Rs. {format_b_signage:,.2f}", styles['Normal'])],
        [Paragraph('Information Technology', styles['Normal']), Paragraph(f"Rs. {format_b_it:,.2f}", styles['Normal'])],
        [Paragraph('Visual Merchandising', styles['Normal']), Paragraph(f"Rs. {format_b_visual:,.2f}", styles['Normal'])],
        [Paragraph('Plumbing', styles['Normal']), Paragraph(f"Rs. {format_b_plumbing:,.2f}", styles['Normal'])],
        [Paragraph('Others', styles['Normal']), Paragraph(f"Rs. {format_b_others:,.2f}", styles['Normal'])],
        [Paragraph('<b>Total Investments</b>', styles['Normal']), Paragraph(f"<b>Rs. {format_b_total:,.2f}</b>", styles['Normal'])]
    ]
    capex_b_table = Table(capex_b_data, colWidths=[2.5*inch, 1.5*inch])
    capex_b_table.setStyle(TableStyle([
        ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
        ('VALIGN', (0, 0), (-1, -1), 'TOP'),
        ('BACKGROUND', (0, -1), (-1, -1), colors.lightgrey),
        ('GRID', (0, 0), (-1, -1), 0.5, colors.black),
        ('WORDWRAP', (0, 0), (-1, -1), True),
        ('LEFTPADDING', (0, 0), (-1, -1), 4),
        ('RIGHTPADDING', (0, 0), (-1, -1), 4),
        ('TOPPADDING', (0, 0), (-1, -1), 4),
        ('BOTTOMPADDING', (0, 0), (-1, -1), 4)
    ]))
    story.append(capex_b_table)
    story.append(Spacer(1, 20))
    
    # Depreciation Method Section
    story.append(Paragraph("Depreciation Method", section_style))
    story.append(Spacer(1, 10))

    depreciation_data = [
        [Paragraph('Depreciation Method', styles['Normal']), Paragraph(report.depreciation.depreciation_method or "Not Set", styles['Normal'])],
        [Paragraph('Depreciation Years (in Years)', styles['Normal']), Paragraph(str(report.depreciation.slm_years or 0), styles['Normal'])]
    ]

    depreciation_table = Table(depreciation_data, colWidths=[3*inch, 2*inch])
    depreciation_table.setStyle(TableStyle([
        ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
        ('VALIGN', (0, 0), (-1, -1), 'TOP'),
        ('GRID', (0, 0), (-1, -1), 0.5, colors.black),
        ('WORDWRAP', (0, 0), (-1, -1), True),
        ('LEFTPADDING', (0, 0), (-1, -1), 6),
        ('RIGHTPADDING', (0, 0), (-1, -1), 6),
        ('TOPPADDING', (0, 0), (-1, -1), 6),
        ('BOTTOMPADDING', (0, 0), (-1, -1), 6)
    ]))
    story.append(depreciation_table)
    
    doc.build(story)
    buffer.seek(0)
    return Response(
        content=buffer.getvalue(),
        media_type="application/pdf",
        headers={"Content-Disposition": "attachment; filename=module1_report.pdf"}
    )


@module_1_report_router.get("/{group_id}/preview-report-pdf1")
async def generate_and_serve_pdf(
    group_id: int,
    db: Session = Depends(get_db),
    token: JWTPayloadSchema = Depends(get_current_student)
):
    """Generate PDF report and return file path information"""
    try:
        service = Module1ReportService(db,token)
        file_path = service.generate_and_save_pdf(group_id)
        
        return {
            "group_id": group_id,
            "file_path": file_path,
        }
            
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Error generating PDF: {str(e)}")
