"""
API endpoints للتقارير - PDF و Excel
"""
from typing import Optional
from uuid import UUID
from fastapi import APIRouter, Depends, Query, Response
from fastapi.responses import StreamingResponse
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select
import io

from app.database import get_db
from app.models.user import User
from app.models.device import Device
from app.models.alert import AlertLog
from app.models.tenant import Tenant
from app.api.deps import get_current_user
from app.services.reports import report_service
from app.core.permissions import UserRole

router = APIRouter()


@router.get("/devices/pdf")
async def export_devices_pdf(
    current_user: User = Depends(get_current_user),
    db: AsyncSession = Depends(get_db)
):
    """تصدير تقرير الأجهزة كـ PDF"""
    # جلب الأجهزة
    query = select(Device).where(Device.tenant_id == current_user.tenant_id)
    result = await db.execute(query)
    devices = result.scalars().all()
    
    # جلب اسم المستأجر
    tenant = await db.get(Tenant, current_user.tenant_id)
    tenant_name = tenant.name if tenant else "SmartLife"
    
    # تحويل الأجهزة إلى قواميس
    devices_data = []
    for device in devices:
        devices_data.append({
            'id': str(device.id),
            'name': device.name,
            'device_type': device.device_type,
            'is_online': device.is_online,
            'device_metadata': device.device_metadata,
            'location': device.location,
            'updated_at': str(device.updated_at) if device.updated_at else None
        })
    
    # إنشاء PDF
    pdf_bytes = report_service.generate_devices_pdf(devices_data, tenant_name)
    
    return Response(
        content=pdf_bytes,
        media_type="application/pdf",
        headers={
            "Content-Disposition": f"attachment; filename=devices_report_{tenant_name}.pdf"
        }
    )


@router.get("/devices/excel")
async def export_devices_excel(
    current_user: User = Depends(get_current_user),
    db: AsyncSession = Depends(get_db)
):
    """تصدير تقرير الأجهزة كـ Excel"""
    query = select(Device).where(Device.tenant_id == current_user.tenant_id)
    result = await db.execute(query)
    devices = result.scalars().all()
    
    tenant = await db.get(Tenant, current_user.tenant_id)
    tenant_name = tenant.name if tenant else "SmartLife"
    
    devices_data = []
    for device in devices:
        devices_data.append({
            'id': str(device.id),
            'name': device.name,
            'device_type': device.device_type,
            'is_online': device.is_online,
            'device_metadata': device.device_metadata,
            'location': device.location,
            'updated_at': str(device.updated_at) if device.updated_at else None
        })
    
    excel_bytes = report_service.generate_devices_excel(devices_data, tenant_name)
    
    return Response(
        content=excel_bytes,
        media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        headers={
            "Content-Disposition": f"attachment; filename=devices_report_{tenant_name}.xlsx"
        }
    )


@router.get("/alerts/pdf")
async def export_alerts_pdf(
    severity: Optional[str] = None,
    is_resolved: Optional[bool] = None,
    current_user: User = Depends(get_current_user),
    db: AsyncSession = Depends(get_db)
):
    """تصدير تقرير التنبيهات كـ PDF"""
    from sqlalchemy.orm import selectinload

    query = select(AlertLog).options(selectinload(AlertLog.device)).where(AlertLog.tenant_id == current_user.tenant_id)

    if severity:
        query = query.where(AlertLog.severity == severity)
    if is_resolved is not None:
        query = query.where(AlertLog.is_resolved == is_resolved)

    query = query.order_by(AlertLog.triggered_at.desc()).limit(500)
    result = await db.execute(query)
    alerts = result.scalars().all()

    tenant = await db.get(Tenant, current_user.tenant_id)
    tenant_name = tenant.name if tenant else "SmartLife"

    alerts_data = []
    for alert in alerts:
        device_name = alert.device.name if alert.device else "N/A"
        alerts_data.append({
            'id': alert.id,
            'title': alert.title,
            'device_name': device_name,
            'severity': alert.severity,
            'is_resolved': alert.is_resolved,
            'triggered_at': str(alert.triggered_at) if alert.triggered_at else None,
            'resolved_at': str(alert.resolved_at) if alert.resolved_at else None,
            'triggered_value': str(alert.reading_value) if alert.reading_value else None,
            'threshold_value': None
        })

    pdf_bytes = report_service.generate_alerts_pdf(alerts_data, tenant_name)

    return Response(
        content=pdf_bytes,
        media_type="application/pdf",
        headers={
            "Content-Disposition": f"attachment; filename=alerts_report_{tenant_name}.pdf"
        }
    )


@router.get("/alerts/excel")
async def export_alerts_excel(
    severity: Optional[str] = None,
    is_resolved: Optional[bool] = None,
    current_user: User = Depends(get_current_user),
    db: AsyncSession = Depends(get_db)
):
    """تصدير تقرير التنبيهات كـ Excel"""
    from sqlalchemy.orm import selectinload

    query = select(AlertLog).options(selectinload(AlertLog.device)).where(AlertLog.tenant_id == current_user.tenant_id)

    if severity:
        query = query.where(AlertLog.severity == severity)
    if is_resolved is not None:
        query = query.where(AlertLog.is_resolved == is_resolved)

    query = query.order_by(AlertLog.triggered_at.desc()).limit(500)
    result = await db.execute(query)
    alerts = result.scalars().all()

    tenant = await db.get(Tenant, current_user.tenant_id)
    tenant_name = tenant.name if tenant else "SmartLife"

    alerts_data = []
    for alert in alerts:
        device_name = alert.device.name if alert.device else "N/A"
        alerts_data.append({
            'id': alert.id,
            'title': alert.title,
            'device_name': device_name,
            'severity': alert.severity,
            'is_resolved': alert.is_resolved,
            'triggered_at': str(alert.triggered_at) if alert.triggered_at else None,
            'resolved_at': str(alert.resolved_at) if alert.resolved_at else None,
            'triggered_value': str(alert.reading_value) if alert.reading_value else None,
            'threshold_value': None
        })

    excel_bytes = report_service.generate_alerts_excel(alerts_data, tenant_name)

    return Response(
        content=excel_bytes,
        media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        headers={
            "Content-Disposition": f"attachment; filename=alerts_report_{tenant_name}.xlsx"
        }
    )
