from flask import Flask, jsonify
from flask_cors import CORS
from sqlalchemy import event
from sqlalchemy.engine import Engine
from sqlite3 import Connection as SQLite3Connection
from werkzeug.exceptions import HTTPException

from models import db
from routes import bp
from config import Config


# Enable WAL mode on every new SQLite connection for better concurrent read performance.
# Registered at module level so it fires exactly once regardless of how many times
# create_app is called (e.g. in tests).
@event.listens_for(Engine, "connect")
def set_sqlite_pragma(dbapi_connection, connection_record):
    if isinstance(dbapi_connection, SQLite3Connection):
        cursor = dbapi_connection.cursor()
        cursor.execute("PRAGMA journal_mode=WAL")
        cursor.close()


def create_app(config_class=Config):
    app = Flask(__name__)
    app.config.from_object(config_class)

    db.init_app(app)
    app.register_blueprint(bp)

    # Allow cross-origin requests from any domain — auth is enforced by API keys, not origin
    CORS(app)

    # Return JSON for all HTTP exceptions (abort() calls) instead of HTML
    @app.errorhandler(HTTPException)
    def handle_http_exception(e):
        return jsonify({"error": e.description}), e.code

    with app.app_context():
        db.create_all()

    return app


if __name__ == "__main__":
    app = create_app()
    app.run(debug=app.config["DEBUG"])
