# IMPORTS
from flask import Flask, render_template, request
from os import getenv as env
import logging

try:
    import src.pg_log as pg_log
except ImportError:
    import pg_log
    from dotenv import load_dotenv
    load_dotenv()


# LOGGING
pg_log_handler = pg_log.PgLog(
    host = env("PG_HOST"),
    port = env("PG_PORT"),
    dbname = env("PG_DBNAME"),
    user= env("PG_USER"),
    password = env("PG_PASSWORD")
)
pg_log_handler.setLevel(logging.DEBUG)

stream_log_handler = logging.StreamHandler()
stream_log_handler.setFormatter(
    logging.Formatter("%(asctime)s - %(levelname)s: %(message)s")
)
stream_log_handler.setLevel(logging.INFO)

log = logging.getLogger(__name__)
log.setLevel(logging.DEBUG)
log.addHandler(stream_log_handler)
log.addHandler(pg_log_handler)

werkzeug_logger = logging.getLogger("werkzeug")
werkzeug_logger.setLevel(logging.DEBUG)
werkzeug_logger.addHandler(pg_log_handler)
werkzeug_logger.addHandler(stream_log_handler)

log.info("Logging initialized.")


try:
    import src.dynamic as dynamic
    import src.errors as errors
    import src.music_metadata as music_metadata
except ImportError:
    import dynamic, errors, music_metadata


# CREATE FLASK APP
app = Flask(
    __name__,
    template_folder="../templates",
    static_folder="../static"
)
log.info("Flask initialized.")


# BLUEPRINTS
app.register_blueprint(errors.bp, url_prefix="/errors")
app.register_blueprint(music_metadata.bp, url_prefix="/music")
app.register_blueprint(dynamic.bp, url_prefix="/")
log.info("Blueprints registered.")


# ROUTES
@app.route("/")
def index():
    return render_template("index.html")

@app.route("/toaster")
def toaster():
    return render_template("toaster.html")

@app.route("/terminal")
def terminal():
    return render_template("terminal.html")


# DEBUG (DONT RUN LIKE THIS IN PROD)
if __name__ == "__main__":
    log.warning(f"RUNNING IN DEBUG MODE DO NOT USE FOR PRODUCTION!")
    app.run(debug=True)