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

from flask import Flask
from config import Config
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.init_app(app)  # 初始化 JWT

    # 允许所有 /api/ 开头的请求跨域，支持 credentials
    cors.init_app(app, resources={r"/*": {"origins": "*"}}, supports_credentials=True)

    # =========================================================
    # 2. 注册蓝图 (Blueprints)
    # ---------------------------------------------------------
    # 注意：为了解决前端请求不带 /v1 导致的 404 错误，
    # 下面的模块都采用了 "双重注册" 策略：
    # 1. 标准地址: /api/v1/...
    # 2. 兼容地址: /api/... (name 参数必须不同)
    # =========================================================

    # -----------------------------------------------------
    # 2.0 注册权限与认证模块 (Auth)
    # -----------------------------------------------------
    try:
        from app.api.v1.auth import auth_bp
        # 标准
        app.register_blueprint(auth_bp, url_prefix='/api/v1/auth')
        # 兼容 (防止前端忘记写 v1)
        app.register_blueprint(auth_bp, url_prefix='/api/auth', name='auth_legacy')
        print("✅ Auth 模块注册成功")
    except ImportError as e:
        print(f"❌ 错误: Auth 模块导入失败: {e}")

    # -----------------------------------------------------
    # 2.1 注册入库聚合模块 (Inbound)
    # -----------------------------------------------------
    try:
        from app.api.v1.inbound import inbound_bp
        # 标准: /api/v1/inbound/base/list
        app.register_blueprint(inbound_bp, url_prefix='/api/v1/inbound')

        # 兼容: /api/inbound/base/list (修复前端 404)
        app.register_blueprint(inbound_bp, url_prefix='/api/inbound', name='inbound_legacy')
        print("✅ Inbound 模块注册成功 (已启用兼容模式: /api/inbound)")
    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')
        app.register_blueprint(print_bp, url_prefix='/api/common/print', name='print_legacy')
        print("✅ Print 模块注册成功")
    except ImportError as e:
        print(f"❌ 错误: Print 模块导入失败: {e}")

    # -----------------------------------------------------
    # 2.3 注册通用上传模块 (Common Upload)
    # -----------------------------------------------------
    try:
        from app.api.v1.common.upload import upload_bp
        app.register_blueprint(upload_bp, url_prefix='/api/v1/common')
        app.register_blueprint(upload_bp, url_prefix='/api/common', name='upload_legacy')
        print("✅ Upload 模块注册成功")
    except ImportError as e:
        print(f"❌ 错误: Upload 模块导入失败: {e}")

    # -----------------------------------------------------
    # 2.4 注册业务操作模块 (Transactions - 借还/维修/报废)
    # ★★★ 关键修改：将前缀改为 /api/v1/transactions 以匹配前端请求 ★★★
    # -----------------------------------------------------
    try:
        from app.api.v1.transactions import trans_bp
        # 标准: /api/v1/transactions/borrow
        app.register_blueprint(trans_bp, url_prefix='/api/v1/transactions')
        # 兼容: /api/transactions/borrow
        app.register_blueprint(trans_bp, url_prefix='/api/transactions', name='trans_legacy')
        print("✅ Transactions 模块注册成功")
    except ImportError as e:
        # 允许模块不存在时不崩溃，但在开发借还功能时这里报错说明 trans_bp 定义有问题
        print(f"⚠️ 提示: Transaction 模块导入失败 (请检查 app/api/v1/transactions.py): {e}")

    # -----------------------------------------------------
    # 2.5 注册出库模块 (Outbound)
    # -----------------------------------------------------
    try:
        from app.api.v1.outbound import outbound_bp
        # 标准: /api/v1/outbound
        app.register_blueprint(outbound_bp, url_prefix='/api/v1/outbound')
        # 兼容: /api/outbound
        app.register_blueprint(outbound_bp, url_prefix='/api/outbound', name='outbound_legacy')
        print("✅ Outbound 模块注册成功")
    except ImportError as e:
        print(f"❌ 错误: Outbound 模块导入失败: {e}")

    # -----------------------------------------------------
    # 2.6 注册 BOM 模块
    # -----------------------------------------------------
    try:
        from app.api.v1.bom import bom_bp
        # 标准: /api/v1/bom
        app.register_blueprint(bom_bp, url_prefix='/api/v1/bom')
        # 兼容: /api/bom
        app.register_blueprint(bom_bp, url_prefix='/api/bom', name='bom_legacy')
        print("✅ BOM 模块注册成功")
    except ImportError as e:
        print(f"❌ 错误: BOM 模块导入失败: {e}")

    # =========================================================
    # 3. 预加载数据模型
    # =========================================================
    with app.app_context():
        try:
            # 基础与库存模型
            from app.models.base import MaterialBase
            from app.models.inbound.buy import StockBuy
            from app.models.inbound.semi import StockSemi
            from app.models.inbound.product import StockProduct

            # 出库模型
            from app.models.outbound import TransOutbound

            # 系统与业务模型
            from app.models.system import SysUser, SysLog
            # 确保借还模型被加载
            from app.models.transaction import TransBorrow, TransRepair, TransScrap

            # 首次运行时可取消注释自动建表 (但在生产环境建议使用 flask db upgrade)
            # db.create_all()

        except ImportError as e:
            print(f"⚠️ 模型预加载部分失败 (检查是否缺少文件): {e}")
        except Exception as e:
            print(f"⚠️ 模型预加载发生未知错误: {e}")

    return app
