from flask import Flask
from app import routes
from app.config import config
from app.context import db
from app.log import Log
from flask_docs import ApiDoc
from flask_cors import CORS


def create_api_doc(app: Flask):
    """
    https://pypi.org/project/Flask-Docs/

    :param app:
    :return:
    """
    # api 文档地址 /docs/api
    app.config["API_DOC_URL_PREFIX"] = "/docs/api"
    # api bp生效前缀
    app.config["API_DOC_MEMBER"] = [
        "ai_bp",
    ]
    app.config["API_DOC_ENABLE"] = True
    # echo -n admin | shasum -a 256
    # 密码admin
    app.config["API_DOC_PASSWORD_SHA2"] = "8c6976e5b5410415bde908bd4dee15dfb167a9c873fc4bb8a81f6f2ab448a918"
    ApiDoc(
        app,
        title="亚声威格py_gpt",
        version="1.0.0",
        description="亚声威格ai Api文档",
    )
    pass


# flask run命令会自动调用create_app函数 https://dormousehole.readthedocs.io/en/latest/cli.html
# 通过flask run启动时，可以通过设置FLASK_APP=app:create_app('development')来指定create_app的参数
# /opt/module/anaconda3/envs/pyspark/bin/python3.8 -m flask run
# python -m flask run
def create_app(config_name='default'):
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)
    # 设置全局允许跨域
    CORS(app, supports_credentials=True)

    Log.init_app(app)
    routes.init_app(app)
    db.init_app(app)

    #  创建文档
    create_api_doc(app)
    return app
