from functools import wraps
import datetime
from flask import request, g
from db_config import get_db_connection

def track_usage(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        try:
            path = request.path
            now = datetime.datetime.utcnow().date()

            conn = get_db_connection()
            cursor = conn.cursor()
            cursor.execute("""
                INSERT INTO api_usage (endpoint, date)
                VALUES (%s, %s)
                ON DUPLICATE KEY UPDATE total = total + 1
            """, (path, now))
            conn.commit()
            cursor.close()
            conn.close()
        except Exception as e:
            print(f"❌ Failed to track usage: {e}")
        return func(*args, **kwargs)
    return wrapper

def get_api_usage():
    try:
        conn = get_db_connection()
        cursor = conn.cursor(dictionary=True)

        seven_days_ago = (datetime.datetime.utcnow().date() - datetime.timedelta(days=6))

        cursor.execute("""
            SELECT date, SUM(total) as total
            FROM api_usage
            WHERE date >= %s
            GROUP BY date
            ORDER BY date ASC
        """, (seven_days_ago,))

        usage = cursor.fetchall()
        cursor.close()
        conn.close()

        return [{ "usage": usage }, 200]
    except Exception as e:
        print(f"❌ Failed to get API usage: {e}")
        return [{ "error": str(e) }, 500]
