"""
Equipment Repository
"""

from typing import Optional, List, Dict, Any
from sqlalchemy import select, func, and_
from sqlalchemy.ext.asyncio import AsyncSession
from uuid import UUID
import structlog

from app.repositories.base import ProductionBaseRepository
from app.models.production import Equipment, EquipmentStatus, EquipmentType

logger = structlog.get_logger()


class EquipmentRepository(ProductionBaseRepository):
    """Repository for equipment operations"""

    def __init__(self, session: AsyncSession):
        super().__init__(Equipment, session)

    async def get_equipment_filtered(
        self,
        filters: Dict[str, Any],
        page: int = 1,
        page_size: int = 50
    ) -> List[Equipment]:
        """Get equipment list with filters and pagination"""
        try:
            # Build base query
            query = select(Equipment).filter(Equipment.tenant_id == UUID(filters.get("tenant_id")))

            # Apply status filter
            if "status" in filters and filters["status"]:
                query = query.filter(Equipment.status == filters["status"])

            # Apply type filter
            if "type" in filters and filters["type"]:
                query = query.filter(Equipment.type == filters["type"])

            # Apply active filter
            if "is_active" in filters and filters["is_active"] is not None:
                query = query.filter(Equipment.is_active == filters["is_active"])

            # Apply pagination
            query = query.order_by(Equipment.created_at.desc())
            query = query.offset((page - 1) * page_size).limit(page_size)

            result = await self.session.execute(query)
            return list(result.scalars().all())

        except Exception as e:
            logger.error("Error getting filtered equipment", error=str(e), filters=filters)
            raise

    async def count_equipment_filtered(self, filters: Dict[str, Any]) -> int:
        """Count equipment matching filters"""
        try:
            # Build base query
            query = select(func.count(Equipment.id)).filter(
                Equipment.tenant_id == UUID(filters.get("tenant_id"))
            )

            # Apply status filter
            if "status" in filters and filters["status"]:
                query = query.filter(Equipment.status == filters["status"])

            # Apply type filter
            if "type" in filters and filters["type"]:
                query = query.filter(Equipment.type == filters["type"])

            # Apply active filter
            if "is_active" in filters and filters["is_active"] is not None:
                query = query.filter(Equipment.is_active == filters["is_active"])

            result = await self.session.execute(query)
            return result.scalar() or 0

        except Exception as e:
            logger.error("Error counting filtered equipment", error=str(e), filters=filters)
            raise

    async def get_equipment_by_id(self, tenant_id: UUID, equipment_id: UUID) -> Optional[Equipment]:
        """Get equipment by ID and tenant"""
        try:
            query = select(Equipment).filter(
                and_(
                    Equipment.id == equipment_id,
                    Equipment.tenant_id == tenant_id
                )
            )
            result = await self.session.execute(query)
            return result.scalar_one_or_none()

        except Exception as e:
            logger.error("Error getting equipment by ID",
                        error=str(e),
                        equipment_id=str(equipment_id),
                        tenant_id=str(tenant_id))
            raise

    async def create_equipment(self, equipment_data: Dict[str, Any]) -> Equipment:
        """Create new equipment"""
        try:
            equipment = Equipment(**equipment_data)
            self.session.add(equipment)
            await self.session.flush()
            await self.session.refresh(equipment)
            return equipment

        except Exception as e:
            logger.error("Error creating equipment", error=str(e), data=equipment_data)
            raise

    async def update_equipment(
        self,
        equipment_id: UUID,
        updates: Dict[str, Any]
    ) -> Optional[Equipment]:
        """Update equipment"""
        try:
            equipment = await self.get(equipment_id)
            if not equipment:
                return None

            for key, value in updates.items():
                if hasattr(equipment, key) and value is not None:
                    setattr(equipment, key, value)

            await self.session.flush()
            await self.session.refresh(equipment)
            return equipment

        except Exception as e:
            logger.error("Error updating equipment", error=str(e), equipment_id=str(equipment_id))
            raise

    async def delete_equipment(self, equipment_id: UUID) -> bool:
        """Soft delete equipment (set is_active to False)"""
        try:
            equipment = await self.get(equipment_id)
            if not equipment:
                return False

            equipment.is_active = False
            await self.session.flush()
            return True

        except Exception as e:
            logger.error("Error deleting equipment", error=str(e), equipment_id=str(equipment_id))
            raise

    async def hard_delete_equipment(self, equipment_id: UUID) -> bool:
        """Permanently delete equipment from database"""
        try:
            equipment = await self.get(equipment_id)
            if not equipment:
                return False

            await self.session.delete(equipment)
            await self.session.flush()
            return True

        except Exception as e:
            logger.error("Error hard deleting equipment", error=str(e), equipment_id=str(equipment_id))
            raise

    async def get_equipment_deletion_summary(self, tenant_id: UUID, equipment_id: UUID) -> Dict[str, Any]:
        """Get summary of what will be affected by deleting equipment"""
        try:
            equipment = await self.get_equipment_by_id(tenant_id, equipment_id)
            if not equipment:
                return {
                    "can_delete": False,
                    "warnings": ["Equipment not found"],
                    "production_batches_count": 0,
                    "maintenance_records_count": 0,
                    "temperature_logs_count": 0
                }

            # Check for related production batches
            from app.models.production import ProductionBatch
            batch_query = select(func.count(ProductionBatch.id)).filter(
                and_(
                    ProductionBatch.tenant_id == tenant_id,
                    ProductionBatch.equipment_id == equipment_id
                )
            )
            batch_result = await self.session.execute(batch_query)
            batches_count = batch_result.scalar() or 0

            # For now, we'll use placeholder counts for maintenance and temperature logs
            # These would need to be implemented based on your actual models
            maintenance_count = 0
            temperature_logs_count = 0

            warnings = []
            if batches_count > 0:
                warnings.append(f"{batches_count} production batch(es) are using this equipment")

            # Equipment can be deleted even with dependencies, but warn the user
            can_delete = True

            return {
                "can_delete": can_delete,
                "warnings": warnings,
                "production_batches_count": batches_count,
                "maintenance_records_count": maintenance_count,
                "temperature_logs_count": temperature_logs_count,
                "equipment_name": equipment.name,
                "equipment_type": equipment.type.value,
                "equipment_location": equipment.location
            }

        except Exception as e:
            logger.error("Error getting equipment deletion summary",
                        error=str(e),
                        equipment_id=str(equipment_id),
                        tenant_id=str(tenant_id))
            raise
