import os
import sqlite3

from flask import Flask

from wurker.settings import conf


def _ui_db_ready(db_path: str) -> bool:
    if not os.path.exists(db_path):
        return False

    conn = sqlite3.connect(db_path)
    try:
        cursor = conn.execute(
            "SELECT name FROM sqlite_master WHERE type='table' AND name IN ('user', 'api_auth')"
        )
        tables = {row[0] for row in cursor.fetchall()}
        return tables == {"user", "api_auth"}
    finally:
        conn.close()


def create_app():
    """Create and configure the Wurker UI Flask app."""

    instance_path = conf.data_root
    static_folder = os.path.join(conf.app_root, "ui", "static")

    app = Flask(
        __name__,
        instance_path=instance_path,
        static_folder=static_folder,
        static_url_path="/static",
        instance_relative_config=True
    )

    app.config.from_mapping(
        SECRET_KEY='dev',
        DATABASE=os.path.join(app.instance_path, 'wurker.db'),
    )

    # ensure the instance folder exists
    try:
        os.makedirs(app.instance_path)
    except OSError:
        pass

    # Init the app DB
    from . import db
    db.init_app(app)

    # Auto-initialize the UI DB on first run to avoid manual setup.
    db_path = app.config["DATABASE"]
    if not _ui_db_ready(db_path):
        with app.app_context():
            db.init_db()

    # Init the auth blueprint
    from . import auth
    app.register_blueprint(auth.bp)

    # Init the dashboard blueprint
    from . import index
    app.register_blueprint(index.bp)
    app.add_url_rule('/', endpoint='index')

    # Init the API blueprint
    from . import api
    app.register_blueprint(api.bp)

    # Init the reports blueprint
    from . import report
    app.register_blueprint(report.bp)

    return app
