"""
Data Retention Service for GDPR compliance.
"""
from sqlalchemy.orm import Session
from typing import Dict, Any, Optional, List
from datetime import datetime, timedelta
from ..models.data_retention import RetentionRule, DataRetentionLog
from ...shared.config.logging_config import get_logger
from ...analytics.services.audit_service import audit_service

logger = get_logger(__name__)

class RetentionService:
    """Service for managing data retention policies and cleanup."""
    
    @staticmethod
    def create_retention_rule(
        db: Session,
        data_category: str,
        retention_period_days: int,
        retention_period_months: Optional[int] = None,
        retention_period_years: Optional[int] = None,
        legal_basis: Optional[str] = None,
        legal_requirement: Optional[str] = None,
        action_after_retention: str = 'anonymize',
        conditions: Optional[Dict[str, Any]] = None,
        description: Optional[str] = None,
        created_by: Optional[int] = None
    ) -> RetentionRule:
        """Create a data retention rule."""
        rule = RetentionRule(
            data_category=data_category,
            retention_period_days=retention_period_days,
            retention_period_months=retention_period_months,
            retention_period_years=retention_period_years,
            legal_basis=legal_basis,
            legal_requirement=legal_requirement,
            action_after_retention=action_after_retention,
            conditions=conditions,
            description=description,
            created_by=created_by,
            is_active=True
        )
        
        db.add(rule)
        db.commit()
        db.refresh(rule)
        
        logger.info(f'Retention rule created: {data_category} - {retention_period_days} days')
        return rule
    
    @staticmethod
    def get_retention_rules(
        db: Session,
        is_active: Optional[bool] = None
    ) -> List[RetentionRule]:
        """Get retention rules."""
        query = db.query(RetentionRule)
        
        if is_active is not None:
            query = query.filter(RetentionRule.is_active == is_active)
        
        return query.order_by(RetentionRule.data_category).all()
    
    @staticmethod
    def get_retention_rule(
        db: Session,
        data_category: str
    ) -> Optional[RetentionRule]:
        """Get retention rule for a specific data category."""
        return db.query(RetentionRule).filter(
            RetentionRule.data_category == data_category,
            RetentionRule.is_active == True
        ).first()
    
    @staticmethod
    async def log_retention_action(
        db: Session,
        retention_rule_id: int,
        data_category: str,
        action_taken: str,
        records_affected: int,
        affected_ids: Optional[List[int]] = None,
        executed_by: Optional[int] = None,
        success: bool = True,
        error_message: Optional[str] = None,
        extra_metadata: Optional[Dict[str, Any]] = None
    ) -> DataRetentionLog:
        """Log a data retention action."""
        log = DataRetentionLog(
            retention_rule_id=retention_rule_id,
            data_category=data_category,
            action_taken=action_taken,
            records_affected=records_affected,
            affected_ids=affected_ids or [],
            executed_by=executed_by,
            executed_at=datetime.utcnow(),
            success=success,
            error_message=error_message,
            extra_metadata=extra_metadata
        )
        
        db.add(log)
        db.commit()
        db.refresh(log)
        
        # Log to audit trail
        await audit_service.log_action(
            db=db,
            action='data_retention_action',
            resource_type='retention_log',
            user_id=executed_by,
            resource_id=log.id,
            details={
                'data_category': data_category,
                'action_taken': action_taken,
                'records_affected': records_affected
            },
            status='success' if success else 'error'
        )
        
        logger.info(f'Retention action logged: {action_taken} on {data_category} - {records_affected} records')
        return log
    
    @staticmethod
    def get_retention_logs(
        db: Session,
        data_category: Optional[str] = None,
        limit: int = 100,
        offset: int = 0
    ) -> List[DataRetentionLog]:
        """Get retention action logs."""
        query = db.query(DataRetentionLog)
        
        if data_category:
            query = query.filter(DataRetentionLog.data_category == data_category)
        
        return query.order_by(DataRetentionLog.executed_at.desc()).offset(offset).limit(limit).all()

retention_service = RetentionService()

