import os
import logging
from datetime import timedelta
from flask import Flask, request
from flask_sqlalchemy import SQLAlchemy
from flask_wtf.csrf import CSRFProtect
from flask_migrate import Migrate
from flask_mail import Mail
from flask_cors import CORS
from config import Config
from .extensions import db, login_manager
from .models import TourType
from .utils import generate_breadcrumbs

# Set up logging
logging.basicConfig(filename='app.log', level=logging.DEBUG)
logger = logging.getLogger(__name__)

# Initialize Flask extensions
mail = Mail()
csrf = CSRFProtect()
migrate = Migrate()

def is_maintenance_mode():
    return False  # Change this to True when you want to enable maintenance mode

def create_app(config_class=Config):
    logger.debug("Starting create_app function")
    app = Flask(__name__)
    app.config.from_object(config_class)

    # Initialize CORS
    CORS(app)

    # Cache configuration
    app.config['SEND_FILE_MAX_AGE_DEFAULT'] = timedelta(days=7)

    logger.debug("Initializing extensions")
    csrf.init_app(app)
    db.init_app(app)
    migrate.init_app(app, db)
    login_manager.init_app(app)
    mail.init_app(app)

    logger.debug("Setting up upload folder")
    app.config['UPLOAD_FOLDER'] = os.path.join(app.root_path, 'static/uploads')
    os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)

    logger.debug("Registering blueprints")
    from .routes import main as main_blueprint
    app.register_blueprint(main_blueprint)
    
    # Verify SECRET_KEY is set
    if 'SECRET_KEY' in app.config:
        logger.info("SECRET_KEY is set in the application config")
        if app.config['SECRET_KEY'] == 'Ami@A08dc@506':
            logger.warning("Default SECRET_KEY is being used.")
    else:
        logger.error("SECRET_KEY is not set in the application config")
    
    with app.app_context():
        from admin import admin_blueprint
        app.register_blueprint(admin_blueprint, url_prefix='/admin')

    # Register service worker route
    @app.route('/service-worker.js')
    def service_worker():
        response = app.send_file('static/js/service-worker.js')
        response.headers['Content-Type'] = 'application/javascript'
        response.headers['Service-Worker-Allowed'] = '/'
        response.headers['Cache-Control'] = 'no-cache'
        return response

    # Register offline route
    @app.route('/offline.html')
    def offline():
        return app.send_file('templates/offline.html')

    # Add response headers
    @app.after_request
    def add_header(response):
        if 'service-worker.js' in request.path:
            response.headers['Cache-Control'] = 'no-cache, no-store, must-revalidate'
            response.headers['Pragma'] = 'no-cache'
            response.headers['Expires'] = '0'
        return response

    logger.debug("Registering CLI commands")
    from .commands import create_admin, init_db
    app.cli.add_command(create_admin)
    app.cli.add_command(init_db)

    @app.context_processor
    def inject_tour_type():
        return dict(TourType=TourType)

    @app.context_processor
    def utility_processor():
        return dict(generate_breadcrumbs=generate_breadcrumbs)

    logger.debug("create_app function completed")
    return app

@login_manager.user_loader
def load_user(user_id):
    from .models import User
    return User.query.get(int(user_id))

logger.debug("Importing models")
from . import models
logger.debug("Models imported") 