from flask import Flask, jsonify
import os
import mysql.connector
from mysql.connector import Error

app = Flask(__name__)

@app.route("/")
def home():
    # Basic endpoint to verify that the app is running
    return "Hello, world! The app is working."

@app.route("/status")
def status():
    # Returns the status of the application
    return jsonify(status="OK")

@app.route("/dbtest")
def dbtest():
    # Attempts to connect to the MySQL database using environment variables
    try:
        connection = mysql.connector.connect(
            host="db",
            user=os.environ.get("MYSQL_USER", "root"),
            password=os.environ.get("MYSQL_PASSWORD", "example"),
            database=os.environ.get("MYSQL_DATABASE", "exampledb"),
            port=3306
        )
        if connection.is_connected():
            connection.close()
            return "Successfully connected to the database."
    except Error as e:
        return f"Error connecting to database: {e}"

if __name__ == "__main__":
    # Run the app on port 5000 and make it accessible from any network interface
    app.run(debug=True, host="0.0.0.0", port=5000)
