from pathlib import Path
from src.config import Config
from src.utils import root_path
from src.routes import api, app_route
from src.database.mysql import create_database
from flask import Flask, render_template, request


def ev_server(path = "") -> Flask:

    static_folder = Path(__file__).parent.parent.joinpath("ev-content")

    ### INIT APP ###
    app = Flask(__name__, static_folder=static_folder, static_url_path="/ev-content")

    app.config['RELATIVE_PATH'] = path

    app.config.from_object(Config)

    @app.errorhandler(404)
    def not_found_handler(e):
        return render_template("404.html"), 404

    ### Register routes ####
    app.register_blueprint(api, url_prefix="/api")
    app.register_blueprint(app_route, url_prefix="/app")

    @app.route("/")
    def app_index():
        return render_template("index.html")

    @app.route("/logger")
    def app_test():
        filename = request.args.get("filename", "info") + ".log"
        logfile = root_path().joinpath("log", filename)

        if not logfile.exists():
            return "El archivo del log no encontrado"

        with open(str(logfile), "r", encoding="UTF-8") as f:
            log_content = f.read().split("\n")
            return render_template("log.html", logs=log_content)

    # Endpoint opcional para inicializar DB (solo dev)
    @app.route("/admin/init-db", methods=["POST", "GET"])
    def init_db():
        if Config.DEBUG == 0:
            return "<h1>Esta en produccion</h1>"
        from flask import current_app

        with current_app.app_context():
            result = create_database()
        status = 500 if result.get("error") else 200
        return result, status

    return app
