from fastapi import APIRouter, Depends, HTTPException, BackgroundTasks
from fastapi.responses import FileResponse
from sqlalchemy.orm import Session
from typing import List
import os

from backend.app.core.database import get_db
from backend.app.api import deps
from backend.app.models import sql_models
from backend.app.schemas import schemas
from backend.app.services.report_service import ReportService

router = APIRouter()

def generate_report_task(report_id: int, db: Session):
    # BackgroundTasks creates a new thread, so we need a new DB session if the passed one is closed?
    # Actually, Depends(get_db) session is closed after request. 
    # Better to create a new session or handle it carefully.
    # For simplicity here, we'll instantiate ReportService which needs a session.
    # But since this runs in background, we should probably handle session lifecycle manually
    # or rely on the fact that if we pass the db session, it might be closed.
    # best practice: create new session scope inside the background task.
    from backend.app.core.database import SessionLocal
    db_bg = SessionLocal()
    try:
        service = ReportService(db_bg, report_id)
        service.generate_pdf()
    finally:
        db_bg.close()

@router.post("/", response_model=schemas.DutyReport)
def create_report(
    report_in: schemas.DutyReportCreate,
    background_tasks: BackgroundTasks,
    db: Session = Depends(get_db),
    current_user: sql_models.User = Depends(deps.get_current_user)
):
    # Use current user name if reporter name is not provided
    if not report_in.reporter_name:
        report_in.reporter_name = current_user.username
        
    db_report = sql_models.DutyReport(
        reporter_name=report_in.reporter_name,
        start_time=report_in.start_time,
        end_time=report_in.end_time,
        status="pending"
    )
    db.add(db_report)
    db.commit()
    db.refresh(db_report)
    
    background_tasks.add_task(generate_report_task, db_report.id, db)
    
    return db_report

@router.get("/", response_model=List[schemas.DutyReport])
def read_reports(
    skip: int = 0,
    limit: int = 10,
    db: Session = Depends(get_db),
    current_user: sql_models.User = Depends(deps.get_current_user)
):
    reports = db.query(sql_models.DutyReport).order_by(sql_models.DutyReport.created_at.desc()).offset(skip).limit(limit).all()
    return reports

@router.get("/{report_id}/download")
def download_report(
    report_id: int,
    db: Session = Depends(get_db),
    current_user: sql_models.User = Depends(deps.get_current_user)
):
    report = db.query(sql_models.DutyReport).filter(sql_models.DutyReport.id == report_id).first()
    if not report:
        raise HTTPException(status_code=404, detail="Report not found")
        
    if report.status != "completed":
        raise HTTPException(status_code=400, detail="Report is not ready yet")
        
    if not report.file_path or not os.path.exists(report.file_path):
        raise HTTPException(status_code=404, detail="Report file not found")
        
    return FileResponse(report.file_path, filename=os.path.basename(report.file_path), media_type='application/pdf')
