import os
import logging
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.orm import DeclarativeBase
from flask_login import LoginManager
from werkzeug.middleware.proxy_fix import ProxyFix

# Set up logging
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)

# Define base class for SQLAlchemy models
class Base(DeclarativeBase):
    pass

# Initialize SQLAlchemy
db = SQLAlchemy(model_class=Base)

# Initialize LoginManager
login_manager = LoginManager()

def create_app(config_class='config.Config'):
    # Create Flask application
    app = Flask(__name__)
    
    # Load configuration
    app.config.from_object(config_class)
    
    # Set secret key
    app.secret_key = os.environ.get("SESSION_SECRET", "gmpl_secret_key_change_in_production")
    
    # Configure ProxyFix for proper URL generation
    app.wsgi_app = ProxyFix(app.wsgi_app, x_proto=1, x_host=1)
    
    # Log de la configuration de base de données
    logger.info(f"Database URL: {app.config.get('SQLALCHEMY_DATABASE_URI', 'Non configurée')}")
    
    # Utiliser la base de données PostgreSQL fournie par l'hébergeur
    app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('DATABASE_URL', 'sqlite:///instance/gmpl.db')
    app.config['SQLALCHEMY_ENGINE_OPTIONS'] = {
        "pool_pre_ping": True,
        "pool_recycle": 300
    }
    logger.info(f"Base de données utilisée: {app.config['SQLALCHEMY_DATABASE_URI']}")

    # Initialize extensions with app
    db.init_app(app)
    login_manager.init_app(app)
    
    # Set login view for LoginManager
    login_manager.login_view = 'admin.login'
    login_manager.login_message = "Veuillez vous connecter pour accéder à cette page."
    login_manager.login_message_category = "warning"
    
    # Import models
    with app.app_context():
        import models
        
        # Create all database tables
        db.create_all()
        
        # Vérifier et corriger les chemins d'images après la création des tables
        try:
            from utils import fix_image_paths
            fix_image_paths()
        except Exception as e:
            app.logger.error(f"Erreur lors de la correction des chemins d'images: {e}")
    
    # Register blueprints
    from routes import main_bp
    from admin_routes import admin_bp
    
    app.register_blueprint(main_bp)
    app.register_blueprint(admin_bp, url_prefix='/admin')
    
    # Configurer le middleware pour le cache-busting si activé
    if app.config.get('IMAGE_CACHE_BUSTING', False):
        from middleware import setup_middleware
        setup_middleware(app)
        app.logger.info("Middleware de cache-busting pour les images activé")
    
    # Configurer les dossiers d'upload
    upload_folder = app.config.get('UPLOAD_FOLDER')
    if upload_folder and not os.path.exists(upload_folder):
        os.makedirs(upload_folder)
        app.logger.info(f"Dossier d'upload créé: {upload_folder}")
    
    # Créer les dossiers pour les images de produits et services
    products_folder = os.path.join(app.static_folder, 'uploads/products')
    services_folder = os.path.join(app.static_folder, 'uploads/services')
    os.makedirs(products_folder, exist_ok=True)
    os.makedirs(services_folder, exist_ok=True)
    app.logger.info(f"Dossiers d'images prêts: {products_folder} et {services_folder}")
    
    # Log de démarrage
    env = 'développement' if app.config.get('DEBUG', False) else 'production'
    app.logger.info(f"Application démarrée en mode {env}")
    
    return app
