"""
Production Service - Tenant Data Deletion
Handles deletion of all production-related data for a tenant
"""
from typing import Dict
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select, delete, func
import structlog

from shared.services.tenant_deletion import BaseTenantDataDeletionService, TenantDataDeletionResult

logger = structlog.get_logger()


class ProductionTenantDeletionService(BaseTenantDataDeletionService):
    """Service for deleting all production-related data for a tenant"""

    def __init__(self, db_session: AsyncSession):
        super().__init__("production-service")
        self.db = db_session

    async def get_tenant_data_preview(self, tenant_id: str) -> Dict[str, int]:
        """Get counts of what would be deleted"""

        try:
            preview = {}

            # Import models here to avoid circular imports
            from app.models.production import (
                ProductionBatch,
                ProductionSchedule,
                Equipment,
                QualityCheck
            )

            # Count production batches
            batch_count = await self.db.scalar(
                select(func.count(ProductionBatch.id)).where(ProductionBatch.tenant_id == tenant_id)
            )
            preview["production_batches"] = batch_count or 0

            # Count production schedules
            try:
                schedule_count = await self.db.scalar(
                    select(func.count(ProductionSchedule.id)).where(ProductionSchedule.tenant_id == tenant_id)
                )
                preview["production_schedules"] = schedule_count or 0
            except Exception:
                # Model might not exist in all versions
                preview["production_schedules"] = 0

            # Count equipment
            try:
                equipment_count = await self.db.scalar(
                    select(func.count(Equipment.id)).where(Equipment.tenant_id == tenant_id)
                )
                preview["equipment"] = equipment_count or 0
            except Exception:
                # Model might not exist in all versions
                preview["equipment"] = 0

            # Count quality checks
            try:
                qc_count = await self.db.scalar(
                    select(func.count(QualityCheck.id)).where(QualityCheck.tenant_id == tenant_id)
                )
                preview["quality_checks"] = qc_count or 0
            except Exception:
                # Model might not exist in all versions
                preview["quality_checks"] = 0

            return preview

        except Exception as e:
            logger.error("Error getting deletion preview",
                        tenant_id=tenant_id,
                        error=str(e))
            return {}

    async def delete_tenant_data(self, tenant_id: str) -> TenantDataDeletionResult:
        """Delete all data for a tenant"""

        result = TenantDataDeletionResult(tenant_id, self.service_name)

        try:
            # Import models here to avoid circular imports
            from app.models.production import (
                ProductionBatch,
                ProductionSchedule,
                Equipment,
                QualityCheck
            )

            # Delete quality checks first (might have FK to batches)
            try:
                qc_delete = await self.db.execute(
                    delete(QualityCheck).where(QualityCheck.tenant_id == tenant_id)
                )
                result.add_deleted_items("quality_checks", qc_delete.rowcount)
            except Exception as e:
                logger.warning("Error deleting quality checks (table might not exist)",
                             tenant_id=tenant_id,
                             error=str(e))
                result.add_error(f"Quality check deletion: {str(e)}")

            # Delete production batches
            try:
                batch_delete = await self.db.execute(
                    delete(ProductionBatch).where(ProductionBatch.tenant_id == tenant_id)
                )
                result.add_deleted_items("production_batches", batch_delete.rowcount)

                logger.info("Deleted production batches for tenant",
                           tenant_id=tenant_id,
                           count=batch_delete.rowcount)

            except Exception as e:
                logger.error("Error deleting production batches",
                           tenant_id=tenant_id,
                           error=str(e))
                result.add_error(f"Production batch deletion: {str(e)}")

            # Delete production schedules
            try:
                schedule_delete = await self.db.execute(
                    delete(ProductionSchedule).where(ProductionSchedule.tenant_id == tenant_id)
                )
                result.add_deleted_items("production_schedules", schedule_delete.rowcount)
            except Exception as e:
                logger.warning("Error deleting production schedules (table might not exist)",
                             tenant_id=tenant_id,
                             error=str(e))
                result.add_error(f"Production schedule deletion: {str(e)}")

            # Delete equipment
            try:
                equipment_delete = await self.db.execute(
                    delete(Equipment).where(Equipment.tenant_id == tenant_id)
                )
                result.add_deleted_items("equipment", equipment_delete.rowcount)
            except Exception as e:
                logger.warning("Error deleting equipment (table might not exist)",
                             tenant_id=tenant_id,
                             error=str(e))
                result.add_error(f"Equipment deletion: {str(e)}")

            # Commit all deletions
            await self.db.commit()

            logger.info("Tenant data deletion completed",
                       tenant_id=tenant_id,
                       deleted_counts=result.deleted_counts)

        except Exception as e:
            logger.error("Fatal error during tenant data deletion",
                        tenant_id=tenant_id,
                        error=str(e))
            await self.db.rollback()
            result.add_error(f"Fatal error: {str(e)}")

        return result
