from flask import Flask, render_template, session, g
from app.models.user import db, User
from app.controllers.user import user_bp
from app.controllers.book import book_bp  # 引入图书蓝图
import os


def create_app():
    app = Flask(__name__)

    # 配置应用
    app.config.from_mapping(
        SECRET_KEY=os.environ.get('SECRET_KEY', 'dev_key_replace_in_production'),
        SQLALCHEMY_DATABASE_URI='mysql+pymysql://book20250428:booksystem@27.124.22.104/book_system',
        SQLALCHEMY_TRACK_MODIFICATIONS=False,
        PERMANENT_SESSION_LIFETIME=86400 * 7,  # 7天

        # 邮件配置
        EMAIL_HOST='smtp.qq.com',
        EMAIL_PORT=587,
        EMAIL_ENCRYPTION='starttls',
        EMAIL_USERNAME='3399560459@qq.com',
        EMAIL_PASSWORD='fzwhyirhbqdzcjgf',  # 这是你的SMTP授权码，不是邮箱密码
        EMAIL_FROM='3399560459@qq.com',
        EMAIL_FROM_NAME='BOOKSYSTEM_OFFICIAL'
    )

    # 实例配置，如果存在
    app.config.from_pyfile('config.py', silent=True)

    # 初始化数据库
    db.init_app(app)

    # 注册蓝图
    app.register_blueprint(user_bp, url_prefix='/user')
    app.register_blueprint(book_bp, url_prefix='/book')  # 注册图书蓝图

    # 创建数据库表
    with app.app_context():
        # 先导入基础模型
        from app.models.user import User, Role
        from app.models.book import Book, Category

        # 创建表
        db.create_all()

        # 再导入依赖模型
        from app.models.borrow import BorrowRecord
        from app.models.inventory import InventoryLog

        # 现在添加反向关系
        # 这样可以确保所有类都已经定义好
        Book.borrow_records = db.relationship('BorrowRecord', backref='book', lazy='dynamic')
        Book.inventory_logs = db.relationship('InventoryLog', backref='book', lazy='dynamic')
        Category.books = db.relationship('Book', backref='category', lazy='dynamic')

        # 创建默认角色
        from app.models.user import Role
        if not Role.query.filter_by(id=1).first():
            admin_role = Role(id=1, role_name='管理员', description='系统管理员')
            db.session.add(admin_role)

        if not Role.query.filter_by(id=2).first():
            user_role = Role(id=2, role_name='普通用户', description='普通用户')
            db.session.add(user_role)

        # 创建管理员账号
        if not User.query.filter_by(username='admin').first():
            admin = User(
                username='admin',
                password='admin123',
                email='admin@example.com',
                role_id=1,
                nickname='系统管理员'
            )
            db.session.add(admin)

        # 创建基础分类
        from app.models.book import Category
        if not Category.query.first():
            categories = [
                Category(name='文学', sort=1),
                Category(name='计算机', sort=2),
                Category(name='历史', sort=3),
                Category(name='科学', sort=4),
                Category(name='艺术', sort=5),
                Category(name='经济', sort=6),
                Category(name='哲学', sort=7),
                Category(name='教育', sort=8)
            ]
            db.session.add_all(categories)

        db.session.commit()

    # 请求前处理
    @app.before_request
    def load_logged_in_user():
        user_id = session.get('user_id')

        if user_id is None:
            g.user = None
        else:
            g.user = User.query.get(user_id)

    # 首页路由
    @app.route('/')
    def index():
        if not g.user:
            return render_template('login.html')
        return render_template('index.html', current_user=g.user)

    # 错误处理
    @app.errorhandler(404)
    def page_not_found(e):
        return render_template('404.html'), 404

    # 模板过滤器
    @app.template_filter('nl2br')
    def nl2br_filter(s):
        if not s:
            return s
        return s.replace('\n', '<br>')

    return app
