import logging
import os

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

import config

db = SQLAlchemy()
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(name)s %(levelname)s %(message)s")


def create_app(start_scheduler=True):
    app = Flask(__name__)
    app.config.from_object(config)
    app.config["SECRET_KEY"] = os.environ.get("SECRET_KEY", os.urandom(24))

    os.makedirs(config.DATA_DIR, exist_ok=True)
    os.makedirs(config.IMAGES_DIR, exist_ok=True)
    os.makedirs(config.ISSUES_DIR, exist_ok=True)

    db.init_app(app)

    with app.app_context():
        from src import models  # noqa: F401
        db.create_all()

        from src.routes import register_blueprints
        register_blueprints(app)

        if start_scheduler:
            from src.scheduler import SchedulerManager
            scheduler_mgr = SchedulerManager(app)
            scheduler_mgr.start()
            app.config["SCHEDULER_MANAGER"] = scheduler_mgr

    return app
