# 文件路径: inventory-backend/app/__init__.py

from flask import Flask
from config import Config
# 【修改】增加 jwt 引入
from app.extensions import db, migrate, cors, jwt
import os


def create_app():
    app = Flask(__name__)
    app.config.from_object(Config)

    # =========================================================
    # 1. 初始化插件
    # =========================================================
    db.init_app(app)
    migrate.init_app(app, db)

    # 【新增】初始化 JWT (用于 Token 认证)
    jwt.init_app(app)

    # 确保跨域配置
    # 允许 /api/ 开头的请求跨域
    cors.init_app(app, resources={r"/*": {"origins": "*"}})

    # =========================================================
    # 2. 注册蓝图 (Blueprints)
    # =========================================================

    # -----------------------------------------------------
    # 2.0 [新增] 注册权限与认证模块 (Auth) - 最关键修复
    # -----------------------------------------------------
    try:
        from app.api.v1.auth import auth_bp
        # 前端请求地址: /api/v1/auth/login
        app.register_blueprint(auth_bp, url_prefix='/api/v1/auth')
        print("✅ Auth (System & Login) 模块注册成功")
    except ImportError as e:
        print(f"❌ 错误: Auth 模块导入失败: {e}")

    # -----------------------------------------------------
    # 2.1 注册入库聚合模块 (Inbound)
    # -----------------------------------------------------
    try:
        from app.api.v1.inbound import inbound_bp
        app.register_blueprint(inbound_bp, url_prefix='/api/v1/inbound')
        print("✅ Inbound (Buy, Semi, Product, Base) 模块注册成功")
    except ImportError as e:
        print(f"❌ 错误: Inbound 模块导入失败: {e}")

    # -----------------------------------------------------
    # 2.2 注册通用打印模块 (Common Print)
    # -----------------------------------------------------
    try:
        from app.api.v1.common.print import print_bp
        app.register_blueprint(print_bp, url_prefix='/api/v1/common/print')
        print("✅ Print (Label Printing) 模块注册成功")
    except ImportError as e:
        print(f"❌ 错误: Print 模块导入失败: {e}")

    # -----------------------------------------------------
    # 2.3 注册通用上传模块 (Common Upload)
    # -----------------------------------------------------
    try:
        from app.api.v1.common.upload import upload_bp
        # 注册方式 1: 标准路径
        app.register_blueprint(upload_bp, url_prefix='/api/v1/common')
        # 注册方式 2: 兼容路径 (防止反向代理剥离 /api)
        app.register_blueprint(upload_bp, url_prefix='/v1/common', name='upload_fallback')
        print("✅ Upload (File Storage) 模块注册成功 (双路径兼容模式)")
    except ImportError as e:
        print(f"❌ 错误: Upload 模块导入失败: {e}")

    # -----------------------------------------------------
    # 2.4 [新增] 注册业务操作模块 (Transactions)
    # -----------------------------------------------------
    try:
        # 对应 borrow, return, scrap 等操作
        from app.api.v1.transactions import trans_bp
        app.register_blueprint(trans_bp, url_prefix='/api/v1/trans')
        print("✅ Transactions (Borrow, Return, Scrap) 模块注册成功")
    except ImportError as e:
        # 如果文件还没写好，这里会报错，但不影响主程序启动
        print(f"⚠️ 警告: Transaction 模块导入失败 (如果是新建项目可忽略): {e}")

    # =========================================================
    # 3. 预加载数据模型 (解决 relationship 找不到模型的问题)
    # =========================================================
    with app.app_context():
        try:
            # 1. 基础物料
            from app.models.base import MaterialBase
            # 2. 采购入库
            from app.models.inbound.buy import StockBuy
            # 3. 半成品入库
            from app.models.inbound.semi import StockSemi
            # 4. 成品入库
            from app.models.inbound.product import StockProduct

            # 【新增】5. 系统用户 (关键：确保创建 user 表)
            from app.models.system import SysUser, SysLog

            # 【新增】6. 业务流水
            from app.models.transaction import TransBorrow, TransRepair, TransScrap

            # 开发环境自动建表 (根据之前的对话，强烈建议在容器第一次启动时开启或手动调用)
            # db.create_all()

        except ImportError as e:
            print(f"⚠️ 模型预加载失败: {e}")
        except Exception as e:
            print(f"⚠️ 模型预加载发生未知错误: {e}")

    return app