"""
Service for managing audit trail retention policies.
"""
from sqlalchemy.orm import Session
from datetime import datetime, timedelta
from typing import Optional, Dict, Any
from ..models.financial_audit_trail import FinancialAuditTrail
from ...shared.config.logging_config import get_logger

logger = get_logger(__name__)


class AuditRetentionService:
    """Service for managing audit trail retention."""
    
    # Default retention period: 7 years (2555 days) - common for financial records
    DEFAULT_RETENTION_DAYS = 2555
    
    # Minimum retention: 1 year (365 days) - legal minimum in many jurisdictions
    MIN_RETENTION_DAYS = 365
    
    # Maximum retention: 10 years (3650 days) - reasonable maximum
    MAX_RETENTION_DAYS = 3650
    
    @staticmethod
    def get_retention_policy() -> Dict[str, Any]:
        """Get current retention policy settings."""
        return {
            'default_retention_days': AuditRetentionService.DEFAULT_RETENTION_DAYS,
            'min_retention_days': AuditRetentionService.MIN_RETENTION_DAYS,
            'max_retention_days': AuditRetentionService.MAX_RETENTION_DAYS,
            'description': 'Financial audit trail retention policy'
        }
    
    @staticmethod
    def get_records_eligible_for_deletion(
        db: Session,
        retention_days: int = DEFAULT_RETENTION_DAYS
    ) -> int:
        """Get count of records eligible for deletion based on retention policy."""
        if retention_days < AuditRetentionService.MIN_RETENTION_DAYS:
            retention_days = AuditRetentionService.MIN_RETENTION_DAYS
        if retention_days > AuditRetentionService.MAX_RETENTION_DAYS:
            retention_days = AuditRetentionService.MAX_RETENTION_DAYS
        
        cutoff_date = datetime.utcnow() - timedelta(days=retention_days)
        
        return db.query(FinancialAuditTrail).filter(
            FinancialAuditTrail.created_at < cutoff_date
        ).count()
    
    @staticmethod
    def get_retention_statistics(
        db: Session,
        retention_days: int = DEFAULT_RETENTION_DAYS
    ) -> Dict[str, Any]:
        """Get statistics about audit trail retention."""
        if retention_days < AuditRetentionService.MIN_RETENTION_DAYS:
            retention_days = AuditRetentionService.MIN_RETENTION_DAYS
        if retention_days > AuditRetentionService.MAX_RETENTION_DAYS:
            retention_days = AuditRetentionService.MAX_RETENTION_DAYS
        
        cutoff_date = datetime.utcnow() - timedelta(days=retention_days)
        
        total_records = db.query(FinancialAuditTrail).count()
        records_to_delete = db.query(FinancialAuditTrail).filter(
            FinancialAuditTrail.created_at < cutoff_date
        ).count()
        records_to_keep = total_records - records_to_delete
        
        oldest_record = db.query(FinancialAuditTrail).order_by(
            FinancialAuditTrail.created_at.asc()
        ).first()
        
        newest_record = db.query(FinancialAuditTrail).order_by(
            FinancialAuditTrail.created_at.desc()
        ).first()
        
        return {
            'retention_days': retention_days,
            'cutoff_date': cutoff_date.isoformat(),
            'total_records': total_records,
            'records_to_keep': records_to_keep,
            'records_to_delete': records_to_delete,
            'oldest_record_date': oldest_record.created_at.isoformat() if oldest_record else None,
            'newest_record_date': newest_record.created_at.isoformat() if newest_record else None,
            'retention_policy': AuditRetentionService.get_retention_policy()
        }


# Singleton instance
audit_retention_service = AuditRetentionService()

