"""
卖相AI - Flask 后端
按功能拆分为蓝图：认证(auth)、主页面(main)、管理员(admin)、图片(image)、品牌(brand)
"""
import os
import secrets
from datetime import timedelta

from flask import Flask
from flask_cors import CORS

from app_common import init_db, BASE_DIR
from blueprints.auth import auth_bp
from blueprints.main import main_bp
from blueprints.admin import admin_bp
from blueprints.image import image_bp
from blueprints.brand import brand_bp


def create_app():
    app = Flask(__name__, template_folder=BASE_DIR, static_folder=BASE_DIR)
    CORS(app)
    app.secret_key = os.environ.get('SECRET_KEY', secrets.token_hex(32))
    app.config['PERMANENT_SESSION_LIFETIME'] = timedelta(days=7)

    # 注册蓝图（不设 url_prefix，保持原有 URL 路径不变，前端无需改动）
    app.register_blueprint(auth_bp)
    app.register_blueprint(main_bp)
    app.register_blueprint(admin_bp)
    app.register_blueprint(image_bp)
    app.register_blueprint(brand_bp)

    return app


app = create_app()


def run_app(host='127.0.0.1', port=5123):
    init_db()
    app.run(host=host, port=port, threaded=True, use_reloader=False)


if __name__ == '__main__':
    run_app()
