# app/__init__.py
from flask import Flask

from config import (
    FLASK_SECRET_KEY,
    PUBLIC_BASE_URL,
    MEDIA_SIGNING_SECRET,
    MEDIA_TOKEN_TTL_SECONDS,
)

from token_store import init_token_db
from db.bulk import init_bulk_db

from app.paths import build_paths
from app.blueprints.ui import bp as ui_bp
from app.blueprints.oauth import bp as oauth_bp
from app.blueprints.media import bp as media_bp
from app.blueprints.bulk_api import bp as bulk_api_bp
from app.blueprints.misc_api import bp as misc_api_bp


def create_app() -> Flask:
    paths = build_paths()

    app = Flask(
        __name__,
        template_folder=paths.templates_dir,
        static_folder=paths.static_dir,
    )
    app.secret_key = FLASK_SECRET_KEY

    # Config pública + media signing
    app.config["PUBLIC_BASE_URL"] = PUBLIC_BASE_URL
    app.config["MEDIA_SIGNING_SECRET"] = MEDIA_SIGNING_SECRET
    app.config["MEDIA_TOKEN_TTL_SECONDS"] = MEDIA_TOKEN_TTL_SECONDS

    # Paths
    app.config["UPLOAD_DIR"] = paths.upload_dir
    app.config["URLPROP_DIR"] = paths.urlprop_dir
    app.config["BULK_DB_PATH"] = paths.bulk_db_path

    # Init DBs
    init_bulk_db(paths.bulk_db_path)
    init_token_db()

    # Register blueprints
    app.register_blueprint(ui_bp)
    app.register_blueprint(oauth_bp)
    app.register_blueprint(media_bp)
    app.register_blueprint(bulk_api_bp)
    app.register_blueprint(misc_api_bp)

    return app
