import logging
from flask import Flask, request, jsonify, redirect, url_for, session

from app.extensions.db import db
from app.extensions.audit_logger import AuditLogger
from app.models import *
from app.models.user import User
from app.routes import register_blueprints
from app.extensions.auth_ext import init_auth, login_manager

from config import Config
from app.routes.dashboard import dashboard_bp
# from backend.api import bp_api




# noinspection SpellCheckingInspection
def create_app() -> Flask:
    app = Flask(__name__, static_url_path='/telezab/static', template_folder='templates')
    app.config.from_object(Config)

    # app.config['SQLALCHEMY_DATABASE_URI'] = config.SQLALCHEMY_DATABASE_URI
    # app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    # app.config['SECRET_KEY'] = config.SECRET_KEY # Замените на надежный секретный ключ
    # app.config['SESSION_COOKIE_SECURE'] = config.SESSION_COOKIE_SECURE # Убедитесь, что установлено значение True
    # app.config['SESSION_COOKIE_HTTPONLY'] = config.SESSION_COOKIE_HTTPONLY # Убедитесь, что установлено значение True
    # app.config['SESSION_COOKIE_SAMESITE'] = config.SESSION_COOKIE_SAMESITE
    # app.config['SESSION_REFRESH_EACH_REQUEST'] = False
    # app.config['PERMANENT_SESSION_LIFETIME'] = config.PERMANENT_SESSION_LIFETIME
    # app.config['SESSION_COOKIE_MAX_AGE'] = 3600
    # app.config['TIMEZONE'] = TZ

    # Инициализация расширений
    db.init_app(app)
    login_manager.init_app(app)
    init_auth(app)
    # Инициализация AuditLogger с передачей db.session
    app.audit_logger = AuditLogger(db.session)

    # Регистрируем блюпринты
    register_blueprints(app)

    # Создаем таблицы (если нужно)
    with app.app_context():
        db.create_all()




    @login_manager.unauthorized_handler
    def unauthorized():
        logging.debug("Unauthorized access detected")
        if request.path.startswith('/telezab/rest/api'):
            return jsonify({'error': 'Не авторизован'}), 401
        else:
            return redirect(url_for('auth.login'))

    @login_manager.user_loader
    def load_user(user_id):
        user_data = session.get('user_data', {})

        display_name = user_data.get('display_name')
        if not display_name:
            display_name = " ".join(filter(None, [
                user_data.get('user_surname'),
                user_data.get('user_name'),
                user_data.get('user_middle_name')
            ]))

        return User(
            user_id,
            user_name=user_data.get('user_name'),
            user_surname=user_data.get('user_surname'),
            user_middle_name=user_data.get('user_middle_name'),
            display_name=display_name,
            email=user_data.get('email')
        )

    return app

