import os

from flask import Flask
from flask_wtf.csrf import CSRFError
from sqlalchemy import text

from config import Config
from extensions import csrf, db
from models import Investment, Plan, RechargeRequest, SystemConfig, User
from routes import register_blueprints
from forms.auth import LATIN_AMERICA_COUNTRIES
from services import get_brand_section, get_brand_value


def create_app():
    app = Flask(__name__)
    app.config.from_object(Config)
    proxy_hops = int(os.environ.get("KIA_PROXY_HOPS", "0"))
    if proxy_hops:
        from werkzeug.middleware.proxy_fix import ProxyFix
        app.wsgi_app = ProxyFix(app.wsgi_app, x_for=proxy_hops, x_proto=proxy_hops)
    for table in db.metadata.tables.values():
        table.dialect_options["mysql"]["engine"] = "InnoDB"
        table.dialect_options["mysql"]["charset"] = "utf8mb4"

    os.makedirs(app.config["UPLOAD_FOLDER"], exist_ok=True)

    db.init_app(app)
    csrf.init_app(app)
    register_blueprints(app)
    from utils.navigation import page_url_for
    app.jinja_env.globals["page_url_for"] = page_url_for

    @app.context_processor
    def inject_brand_config():
        from utils.i18n import get_lang, t

        return {
            "brand_name": get_brand_value("platform_name", "BancaNet"),
            "brand_short_name": get_brand_value("brand_short_name", "BancaNet"),
            "brand_colors": get_brand_section("colors", {}),
            "brand_logo": get_brand_section("logo", {}),
            "brand_home_texts": get_brand_section("home_texts", {}),
            "brand_bank_details": get_brand_section("bank_details", {}),
            "brand_referrals": get_brand_section("referrals", {}),
            "brand_withdrawals": get_brand_section("withdrawals", {}),
            "brand_visible_plans": get_brand_section("visible_plans", {}),
            "latin_america_countries": LATIN_AMERICA_COUNTRIES,
            "lang": get_lang(),
            "t": t,
        }

    from core.request_safety import install_request_safety
    from core.commands import install_commands
    install_request_safety(app)
    install_commands(app)

    @app.errorhandler(CSRFError)
    def handle_csrf_error(error):
        from flask import flash, redirect, request, url_for

        flash("La sesion del formulario expiro o se abrio desde otro host. Recarga la pagina e intenta de nuevo.", "error")
        if request.path.startswith("/admin"):
            return redirect(url_for("admin.settings"))
        return redirect(url_for("auth.login"))

    return app


app = create_app()


if __name__ == "__main__":
    app.run(debug=app.config["DEBUG"])
