from flask import Flask

from modules.users import users_bp
from modules.home.routes import home_bp
from modules.chat.routes import chat_bp
from modules.excel.routes import excel_bp
from modules.health.routes import health_bp
from modules.architecture.routes import architecture_bp
from modules.admin.routes import admin_bp
from modules.auth.routes import auth_bp
from modules.rest.routes import rest_bp

from config_loader import load_config
from modules.excel.queue_manager import start_excel_worker
from modules.users.service import create_user
from modules.users.db import get_pool
import bcrypt
import oracledb
from werkzeug.security import generate_password_hash


def ensure_default_admin():
    """
    Cria admin default direto no Oracle (sem SQLAlchemy)
    """

    pool = get_pool()

    sql_check = "SELECT id FROM app_users WHERE user_role='admin'"
    sql_insert = """
                 INSERT INTO app_users (name,email,user_role,password_hash,active)
                 VALUES (:1,:2,'admin',:3,1) \
                 """

    with pool.acquire() as conn:
        with conn.cursor() as cur:
            cur.execute(sql_check)
            if not cur.fetchone():
                pwd = generate_password_hash("admin123")
                cur.execute(sql_insert, ["Admin", "admin@local", pwd])
                conn.commit()
                print("Default admin created: admin@local / admin123")


def create_app():

    app = Flask(__name__)
    app.secret_key = "super-secret"

    # NÃO EXISTE MAIS SQLite
    # NÃO EXISTE MAIS SQLAlchemy

    start_excel_worker()

    # cria admin no Oracle
    ensure_default_admin()

    app.register_blueprint(users_bp, url_prefix="/admin/users")
    app.register_blueprint(chat_bp)
    app.register_blueprint(excel_bp)
    app.register_blueprint(health_bp)
    app.register_blueprint(architecture_bp)
    app.register_blueprint(home_bp)
    app.register_blueprint(admin_bp, url_prefix="/admin")
    app.register_blueprint(auth_bp)
    app.register_blueprint(rest_bp)

    from modules.core.security import get_current_user

    @app.context_processor
    def inject_user():
        return dict(current_user=get_current_user())

    return app


app = create_app()

config = load_config()
API_BASE_URL = f"{config.app_base}:{config.service_port}"

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=config.service_port)