from flask import Flask, g, render_template
from flask_cors import CORS
from time import time

app = Flask(__name__)
CORS(app)

request_count = 0
start_time = time()
last_response_time = 0

@app.before_request
def count_requests():
    global request_count
    request_count += 1

@app.before_request
def before_request():
    g.start = time()

@app.after_request
def after_request(response):
    global last_response_time

    last_response_time = round((time() - g.start) * 1000, 2)

    return response

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

@app.route("/health")
def health():
    return {
        "status": "healthy"
    }

@app.route("/stats")
def stats():
    uptime = int(time() - start_time)

    return {
        "application": "Ghaymah SRE Exam",
        "status": "healthy",
        "version": "1.0.0",
        "requests": request_count,
        "uptime_seconds": uptime,
        "response_time_ms": last_response_time
    }


if __name__ == "__main__":
    app.run(host="0.0.0.0", port=5000)