from flask import Flask
import config
from db import init_db

from routes.dashboard import bp as dashboard_bp
from routes.flows import bp as flows_bp
from routes.runs import bp as runs_bp
from routes.logs import bp as logs_bp
from routes.internal import bp as internal_bp
from routes.pages import bp as pages_bp


def create_app():
    app = Flask(__name__)
    app.url_map.strict_slashes = False

    init_db()

    app.register_blueprint(dashboard_bp)
    app.register_blueprint(flows_bp)
    app.register_blueprint(runs_bp)
    app.register_blueprint(logs_bp)
    app.register_blueprint(internal_bp)
    app.register_blueprint(pages_bp)

    @app.route('/health')
    def health():
        return {'status': 'ok'}

    return app


application = create_app()

if __name__ == '__main__':
    if config.ENABLE_BACKGROUND_THREAD:
        import threading
        import time
        from services.poll_executions import poll_executions_job
        from services.refresh_flows import refresh_flows_job

        def _loop():
            poll_executions_job()
            refresh_flows_job()
            last_flows_refresh = time.time()
            while True:
                time.sleep(config.EXECUTIONS_POLL_SECONDS)
                poll_executions_job()
                if time.time() - last_flows_refresh >= config.FLOWS_REFRESH_SECONDS:
                    refresh_flows_job()
                    last_flows_refresh = time.time()

        threading.Thread(target=_loop, daemon=True).start()

    application.run(host='0.0.0.0', port=5000, debug=True)
