import os

import click
from flask import Flask
from flask.cli import with_appcontext
from flask_sqlalchemy import SQLAlchemy

__version__ = (1, 0, 0, "dev")

db = SQLAlchemy()


def create_app(test_config=None):
    """Create and configure an instance of the Flask application."""
    app = Flask(__name__, instance_relative_config=True)

    # some deploy systems set the database url in the environ
    db_url = os.environ.get("DATABASE_URL")

    if db_url is None:
        # default to a sqlite database in the instance folder
        db_url = "sqlite:///" + os.path.join(app.instance_path, "flaskr.sqlite")
        # ensure the instance folder exists
        os.makedirs(app.instance_path, exist_ok=True)

    app.config.from_mapping(
        # default secret that should be overridden in environ or config
        SECRET_KEY=os.environ.get("SECRET_KEY", "dev"),
        SQLALCHEMY_DATABASE_URI=db_url,
        SQLALCHEMY_TRACK_MODIFICATIONS=False,
    )

    if test_config is None:
        # load the instance config, if it exists, when not testing
        app.config.from_pyfile("config.py", silent=True)
    else:
        # load the test config if passed in
        app.config.update(test_config)

    # initialize Flask-SQLAlchemy and the init-db command
    db.init_app(app)
    app.cli.add_command(init_db_command)

    # apply the blueprints to the app
    from flaskr import auth, blog

    app.register_blueprint(auth.bp)
    app.register_blueprint(blog.bp)

    # make "index" point at "/", which is handled by "blog.index"
    app.add_url_rule("/", endpoint="index")

    return app


def init_db():
    db.drop_all()
    db.create_all()


@click.command("init-db")
@with_appcontext
def init_db_command():
    """Clear existing data and create new tables."""
    init_db()
    click.echo("Initialized the database.")

[((10, 5, 10, 17), 'flask_sqlalchemy.SQLAlchemy', 'SQLAlchemy', ({}, {}), '()', False, 'from flask_sqlalchemy import SQLAlchemy\n'), ((61, 1, 61, 25), 'click.command', 'click.command', ({(61, 15, 61, 24): '"""init-db"""'}, {}), "('init-db')", False, 'import click\n'), ((15, 10, 15, 56), 'flask.Flask', 'Flask', (), '', False, 'from flask import Flask\n'), ((18, 13, 18, 43), 'os.environ.get', 'os.environ.get', ({(18, 28, 18, 42): '"""DATABASE_URL"""'}, {}), "('DATABASE_URL')", False, 'import os\n'), ((66, 4, 66, 43), 'click.echo', 'click.echo', ({(66, 15, 66, 42): '"""Initialized the database."""'}, {}), "('Initialized the database.')", False, 'import click\n'), ((24, 8, 24, 53), 'os.makedirs', 'os.makedirs', (), '', False, 'import os\n'), ((22, 32, 22, 80), 'os.path.join', 'os.path.join', ({(22, 45, 22, 62): 'app.instance_path', (22, 64, 22, 79): '"""flaskr.sqlite"""'}, {}), "(app.instance_path, 'flaskr.sqlite')", False, 'import os\n'), ((28, 19, 28, 54), 'os.environ.get', 'os.environ.get', ({(28, 34, 28, 46): '"""SECRET_KEY"""', (28, 48, 28, 53): '"""dev"""'}, {}), "('SECRET_KEY', 'dev')", False, 'import os\n')]