from fastapi import APIRouter, Depends, HTTPException
from fastapi.responses import StreamingResponse
from sqlalchemy.orm import Session
from app.models import get_db
from app.services.report_generator import ReportGenerator

router = APIRouter(prefix="/report", tags=["Report"])

@router.get("/export")
def export_report(format: str = "xlsx", db: Session = Depends(get_db)):
    """匯出報表"""
    if format not in ['xlsx', 'pdf']:
        raise HTTPException(status_code=400, detail="Invalid format. Use 'xlsx' or 'pdf'")

    generator = ReportGenerator(db)

    print(f"Export request received. Format: {format}")
    
    if format == 'xlsx':
        try:
            print("Generating Excel...")
            output = generator.generate_excel()
            print("Excel generated successfully.")
            media_type = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
            filename = "dit_attribution_report.xlsx"
        except Exception as e:
            print(f"Error generating Excel: {str(e)}")
            raise HTTPException(status_code=500, detail=str(e))
    else:
        try:
            output = generator.generate_pdf()
            media_type = "application/pdf"
            filename = "dit_attribution_report.pdf"
        except Exception as e:
            print(f"Error generating PDF: {str(e)}")
            raise HTTPException(status_code=500, detail=str(e))

    return StreamingResponse(
        output,
        media_type=media_type,
        headers={
            "Content-Disposition": f"attachment; filename={filename}"
        }
    )
