# app/__init__.py (App-Factory)

import logging
import threading
import time
import os
import pygame

from flask import Flask

from .utils.logging import setup_logging, cleanup_old_log_dirs
from .routes.main import main_bp
from .routes.admin import admin_bp
from .routes.api import api_bp
from .bluetooth.manager import init_bluetooth

logger = logging.getLogger(__name__)  # ← Logger für diese Datei

def create_app():
    app = Flask(__name__,
                template_folder='../templates',  # ← Root/templates statt app/templates
                static_folder='../static')       # ← Root/static

    # Config laden
    app.config.from_object('config.Config')

    # Logging zuerst (vor allem anderen)
    setup_logging(app)

    # Bluetooth initialisieren (Monitor-Thread startet automatisch)
    init_bluetooth()

    # pygame initialisieren (einmalig)
    pygame.mixer.init(frequency=44100, size=-16, channels=2, buffer=512)
    pygame.mixer.music.set_volume(0.8)  # Standard-Lautstärke
    app.logger.info("pygame initialisiert")

    # Blueprints registrieren
    from .routes.main import main_bp
    from .routes.admin import admin_bp
    from .routes.api import api_bp

    # Blueprints registrieren
    app.register_blueprint(main_bp)
    app.register_blueprint(admin_bp, url_prefix='/admin')
    app.register_blueprint(api_bp, url_prefix='/api')

    # Täglicher Cleanup-Thread starten (einmalig)
    def daily_cleanup():
        while True:
            cleanup_old_log_dirs(90)
            time.sleep(86400)  # 24 Stunden

    cleanup_thread = threading.Thread(target=daily_cleanup, daemon=True)
    cleanup_thread.start()
    logger.info("Täglicher Log-Cleanup-Thread gestartet (24h Intervall)")

    return app
