from flask import Flask
from flask_cors import CORS
from . import config
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
import logging
import os
import sqlite3

# 创建 SQLAlchemy 全局实例
db = SQLAlchemy()


# 创建并配置 Flask 应用
def create_app():
    app = Flask(__name__)
    CORS(app)
    app.config.from_object(config.Config)
    app.logger.setLevel(logging.DEBUG)

    # 图片上传目录
    UPLOAD_FOLDER = 'uploads'
    if not os.path.exists(UPLOAD_FOLDER):
        os.makedirs(UPLOAD_FOLDER)
    app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

    # 初始化 SQLAlchemy
    db.init_app(app)

    # 初始化 Flask-Migrate
    migrate = Migrate(app, db)

    # 初始化数据库表
    def init_db():
        conn = sqlite3.connect('software_intro.db')
        cursor = conn.cursor()
        cursor.execute('''
            CREATE TABLE IF NOT EXISTS software_intro (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                title TEXT NOT NULL,
                intro TEXT
            )
        ''')
        conn.commit()
        conn.close()

    # 调用初始化数据库
    init_db()

    # 导入路由
    from . import routes
    app.register_blueprint(routes.bp)

    return app
