import pytest
import os
import sys
import tempfile
import shutil
import uuid

# Add the project directory to sys.path
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))


@pytest.fixture(scope="function")
def app():
    """Create and configure a Flask app for testing."""
    from app import create_app

    # Crear un directorio temporal único para cada prueba
    test_id = str(uuid.uuid4())
    test_storage_dir = tempfile.mkdtemp(prefix=f"arch_test_{test_id}_")

    # Forzar modo testing
    os.environ["FLASK_ENV"] = "testing"
    os.environ["TESTING"] = "True"

    # Crear la aplicación con configuración de prueba
    app = create_app("testing")

    # Asegurar que estamos en modo testing
    app.config["TESTING"] = True
    app.config["ENV"] = "testing"
    app.config["STORAGE_PATH"] = test_storage_dir

    # Create an application context
    with app.app_context():
        yield app

    # Limpiar después de cada prueba
    try:
        shutil.rmtree(test_storage_dir, ignore_errors=True)
    except Exception as e:
        print(f"Error al eliminar directorio de prueba: {e}")


@pytest.fixture
def client(app):
    """A test client for the app."""
    return app.test_client()


@pytest.fixture
def runner(app):
    """A test CLI runner for the app."""
    return app.test_cli_runner()
