from typing import Any, List, Optional
from fastapi import APIRouter, Depends, Query, HTTPException, Body
from fastapi.responses import FileResponse
from sqlalchemy.orm import Session
from backend.app.api import deps
from backend.app.core.database import get_db
from backend.app.models import sql_models
from backend.app.schemas import schemas
import openpyxl
import os
import tempfile
from datetime import datetime

router = APIRouter()

@router.get("", response_model=List[schemas.TaskLog])
def read_logs(
    db: Session = Depends(get_db),
    skip: int = 0,
    limit: int = 100,
    only_alarm: bool = False,
    current_user: sql_models.User = Depends(deps.get_current_user)
) -> Any:
    query = db.query(sql_models.TaskLog)
    if only_alarm:
        query = query.filter(sql_models.TaskLog.is_alarm == True)
    return query.order_by(sql_models.TaskLog.check_time.desc()).offset(skip).limit(limit).all()

@router.delete("/batch")
def delete_logs_batch(
    *,
    db: Session = Depends(get_db),
    log_ids: List[int] = Body(...),
    current_user: sql_models.User = Depends(deps.get_current_user)
) -> Any:
    if not log_ids:
        return {"msg": "No logs selected"}
    
    # Batch delete
    db.query(sql_models.TaskLog).filter(sql_models.TaskLog.id.in_(log_ids)).delete(synchronize_session=False)
    db.commit()
    return {"msg": "Logs deleted successfully"}

@router.get("/export")
def export_logs(
    db: Session = Depends(get_db),
    start_time: Optional[datetime] = None,
    end_time: Optional[datetime] = None,
    current_user: sql_models.User = Depends(deps.get_current_user)
):
    query = db.query(sql_models.TaskLog).order_by(sql_models.TaskLog.check_time.desc())
    
    if start_time:
        query = query.filter(sql_models.TaskLog.check_time >= start_time)
    if end_time:
        query = query.filter(sql_models.TaskLog.check_time <= end_time)
        
    logs = query.limit(5000).all()
    
    wb = openpyxl.Workbook()
    ws = wb.active
    ws.title = "Logs"
    
    # Updated headers
    headers = ["ID", "Task ID", "Camera ID", "Time", "Is Alarm", "Alarm Name", "Alarm Content", "Area", "Image URL"]
    ws.append(headers)
    
    for log in logs:
        ws.append([
            log.id,
            log.task_id,
            log.camera_id,
            log.check_time,
            log.is_alarm,
            log.alarm_name or "",
            log.alarm_content or "",
            log.area or "",
            f"http://localhost:8000{log.snapshot_path}" # TODO: Use dynamic host
        ])
    
    tmp_path = os.path.join(tempfile.gettempdir(), f"logs_{datetime.now().strftime('%Y%m%d%H%M%S')}.xlsx")
    wb.save(tmp_path)
    
    return FileResponse(tmp_path, filename="logs.xlsx", media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
