import os
import sys

import gevent
import time
from flask import current_app


def safe_remove(file_path):
    try:
        if os.path.exists(file_path):
            os.remove(file_path)

            # Wait for the file to be deleted
            start_time = time.time()
            while os.path.exists(file_path):
                gevent.sleep(1)
                if time.time() - start_time > 5:  # 5 second timeout
                    raise TimeoutError(f"Failed to delete {file_path} after 5 seconds")

            current_app.logger.info(f"Successfully deleted {file_path}")
        else:
            current_app.logger.info(f"{file_path} does not exist, skipping deletion")
    except Exception as e:
        current_app.logger.error(f"Error deleting {file_path}: {str(e)}")
        raise


def sync_folder(file_path):
    dir_fd = os.open(file_path, os.O_RDONLY)
    os.fsync(dir_fd)
    os.close(dir_fd)


def get_project_root():
    """Get the root directory of the project."""
    # Use the module that's actually running (not this file)
    module = sys.modules['__main__']
    if hasattr(module, '__file__'):
        # Get the path to the main module
        main_path = os.path.abspath(module.__file__)
        # Get the root directory (where the main module is located)
        return os.path.dirname(main_path)
    else:
        # Fallback: use current working directory
        return os.getcwd()
