import fcntl
import os
import time
from flask import Flask, jsonify
from flask_cors import CORS

app = Flask(__name__)

# السماح للـ dashboard.html بالوصول للـ API من المتصفح
CORS(app)

START_TIME = time.time()

# عداد الطلبات مشترك بين gunicorn workers
COUNTER_FILE = "/tmp/request_count.txt"


def _increment_and_read_count() -> int:
    fd = os.open(COUNTER_FILE, os.O_RDWR | os.O_CREAT, 0o644)

    try:
        fcntl.flock(fd, fcntl.LOCK_EX)

        data = os.read(fd, 64).decode().strip()
        count = int(data) if data else 0

        count += 1

        os.lseek(fd, 0, os.SEEK_SET)
        os.truncate(fd, 0)
        os.write(fd, str(count).encode())

        return count

    finally:
        fcntl.flock(fd, fcntl.LOCK_UN)
        os.close(fd)


def _read_count() -> int:
    if not os.path.exists(COUNTER_FILE):
        return 0

    with open(COUNTER_FILE, "r") as f:
        data = f.read().strip()
        return int(data) if data else 0


@app.before_request
def _count_requests():
    _increment_and_read_count()


@app.route("/")
def home():
    return jsonify({
        "message": "Ghaymah Training API is running",
        "status": "ok"
    })


@app.route("/health")
def health():
    uptime_seconds = round(time.time() - START_TIME, 2)

    return jsonify({
        "status": "healthy",
        "uptime_seconds": uptime_seconds,
        "requests_served": _read_count()
    }), 200


@app.route("/metrics")
def metrics():
    uptime_seconds = round(time.time() - START_TIME, 2)

    return jsonify({
        "uptime_seconds": uptime_seconds,
        "requests_served": _read_count(),
        "start_time": START_TIME
    })


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