"""Flask application factory and initialization."""

import atexit
import os

from flasgger import Swagger
from flask import Flask, send_from_directory
from flask_cors import CORS

from app import config
from app.config import Config
from app.db import Database
from app.functionalities.hippo.routes import hippo_bp
from app.routes import api_bp


def create_app():
    """Create and configure the Flask application."""
    app = Flask(__name__)
    app.config.from_object(Config)

    # Enable CORS for frontend requests
    CORS(app, resources={r"/api/*": {"origins": "*"}})

    if app.config["FLASK_ENV"] == "development":
        app.config["SWAGGER"] = {
            "title": "Hipograf API",
            "uiversion": 3,
            "openapi": "3.0.2",
            "specs_route": "/swagger/",
        }
        Swagger(app, template=config.swagger_template)

    # Initialize MongoDB connection
    Database.connect()

    app.register_blueprint(api_bp, url_prefix="/api")

    # Register HIPPO AI assistant routes
    app.register_blueprint(hippo_bp, url_prefix="/api/hippo")

    # Keep a shared Mongo client for the process lifetime; closing on each
    # request can break in-flight requests when the server handles concurrency.
    atexit.register(Database.disconnect)

    return app
