from fastapi import APIRouter, HTTPException
import os
import shutil
from .upload import session_files
import logging

router = APIRouter(tags=["cleanup"])

# Root directory for uploads
UPLOAD_ROOT = "uploaded_files"

# List of base documents that should not be deleted
BASE_DOCUMENTS = ["the-bitter-lesson", "hurricane-faq", "pokemon-guide"]

@router.delete("/cleanup-session/{session_id}")
async def cleanup_session(session_id: str):
    """
    Removes the session directory after the user has viewed the evaluation results.
    Does not remove base documents.
    In development mode, does nothing and returns a log message.
    
    Args:
        session_id: ID of the session to delete
        
    Returns:
        Dictionary with status and message
    """
    # Check if we are in development mode
    if os.environ.get("ENVIRONEMENT", "").lower() == "development":
    # if True:
        logging.info(f"[DEV MODE] Cleanup called for session: {session_id} - No action taken in development mode")
        return {
            "success": True,
            "message": f"Development mode - cleanup skipped for session: {session_id}"
        }
    
    # Check if the session_id exists and is not a base document
    if session_id in BASE_DOCUMENTS:
        return {
            "success": False,
            "message": f"Cannot delete base document: {session_id}"
        }
    
    session_dir = os.path.join(UPLOAD_ROOT, session_id)
    
    # Check if the directory exists
    if not os.path.exists(session_dir):
        return {
            "success": False,
            "message": f"Session directory not found: {session_id}"
        }
    
    try:
        # Remove the session file reference
        if session_id in session_files:
            del session_files[session_id]
            
        # Remove the session directory
        shutil.rmtree(session_dir)
        
        return {
            "success": True,
            "message": f"Session cleaned up successfully: {session_id}"
        }
    except Exception as e:
        return {
            "success": False,
            "message": f"Error cleaning up session: {str(e)}"
        }