import os
import sys

from yoyo import get_backend, read_migrations

from src.config import Configuration
from src.internals.database import database


def run_web():
    environment_vars = {
        **os.environ.copy(),
        "FLASK_DEBUG": "development" if Configuration().development_mode else "false",
        "NODE_ENV": "development" if Configuration().development_mode else "production",
        "KEMONO_SITE": Configuration().webserver["site"],
        "ICONS_PREPEND": Configuration().webserver["ui"]["files_url_prepend"]["icons_base_url"],
        "BANNERS_PREPEND": Configuration().webserver["ui"]["files_url_prepend"]["banners_base_url"],
        "THUMBNAILS_PREPEND": Configuration().webserver["ui"]["files_url_prepend"]["thumbnails_base_url"],
        "CREATORS_LOCATION": Configuration().webserver["api"]["creators_location"],
    }

    for k, v in environment_vars.items():
        os.environ[k] = v

    database.init()

    try:
        if Configuration().automatic_migrations:
            """Run migrations."""
            backend = get_backend(
                f"postgresql+psycopg://{Configuration().database["user"]}"
                f":{Configuration().database["password"]}"
                f"@{Configuration().database["host"]}:"
                f"{Configuration().database["port"]}"
                f"/{Configuration().database["database"]}"
            )
            migrations = read_migrations("./db/migrations")
            with backend.lock():
                backend.apply_migrations(backend.to_apply(migrations))
            backend.connection.close()
            del backend
            """ Initialize Pgroonga if needed. """
            with database.pool.getconn() as conn:
                # TODO: make it an actual migration file
                try:
                    with conn.cursor() as db:
                        db.execute("CREATE EXTENSION IF NOT EXISTS pgroonga")
                        db.execute(
                            "CREATE INDEX IF NOT EXISTS pgroonga_posts_concat_idx ON posts USING pgroonga ( (title || ' ' || content) );"
                        )
                        db.execute("CREATE INDEX IF NOT EXISTS pgroonga_dms_idx ON dms USING pgroonga (content)")
                    conn.commit()
                except Exception as error:
                    if (Configuration().development_mode):
                        raise Exception("Failed to install PGRoonga.") from error
                    else:
                        pass
                if Configuration().development_mode:
                    with conn.cursor() as db:
                        db.execute(open("db/seed.sql", "r").read())
                database.pool.putconn(conn)
    finally:
        """ "Close" the database pool."""
        database.close_pool()

    from src import server
    server.app.run("0.0.0.0", port=Configuration().webserver['port'])
