import os
import time
import asyncio
import structlog
from pathlib import Path
from app.core.config import settings

logger = structlog.get_logger(__name__)

class CleanupService:
    """
    Service to clean up temporary files and old uploads.
    Enforces retention policy to prevent disk overflow.
    """
    
    def __init__(self):
        self.upload_dir = Path(settings.upload_dir)
        self.max_age_seconds = settings.file_retention_days * 24 * 60 * 60
        self.is_running = False

    async def start(self):
        """Start the background cleanup task."""
        self.is_running = True
        logger.info("cleanup_service_started", retention_days=settings.file_retention_days)
        
        while self.is_running:
            try:
                await self.cleanup()
            except Exception as e:
                logger.error("cleanup_failed", error=str(e))
            
            # Run every hour
            await asyncio.sleep(3600)

    def stop(self):
        """Stop the cleanup service."""
        self.is_running = False
        logger.info("cleanup_service_stopped")

    async def cleanup(self):
        """Run the cleanup logic."""
        logger.info("cleanup_run_started")
        deleted_count = 0
        reclaimed_bytes = 0
        now = time.time()

        if not self.upload_dir.exists():
            return

        for file_path in self.upload_dir.glob("**/*"):
            if not file_path.is_file():
                continue

            # Check file age
            try:
                stat = file_path.stat()
                age = now - stat.st_mtime
                
                if age > self.max_age_seconds:
                    size = stat.st_size
                    file_path.unlink()
                    deleted_count += 1
                    reclaimed_bytes += size
                    logger.debug("file_deleted", path=str(file_path), age_hours=age/3600)
            except Exception as e:
                logger.warning("file_deletion_failed", path=str(file_path), error=str(e))

        if deleted_count > 0:
            logger.info(
                "cleanup_run_completed",
                deleted_files=deleted_count,
                reclaimed_mb=reclaimed_bytes / (1024 * 1024)
            )
