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

try:
    import src.dynamic_routes as dynamic_routes
    import src.errors as errors
    import src.pg_log as pg_log
except ImportError:
    import dynamic_routes, errors, pg_log


# ENV
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.")


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


# BLUEPRINTS
app.register_blueprint(errors.bp, url_prefix="/errors")
app.register_blueprint(dynamic_routes.bp, url_prefix="/")


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

@app.route("/toaster")
def toaster():
    return render_template("toaster.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)