import requests
from datetime import datetime, timedelta
import os

GITLAB_URL = "https://gitlab.allence.cloud"
PRIVATE_TOKEN = os.getenv("PRIVATE_TOKEN")

headers = {
    "Private-Token": PRIVATE_TOKEN
}

threshold_days = 30
threshold_date = datetime.utcnow() - timedelta(days=threshold_days)

EXCLUDED_USERS = [
    "walid.mansia",
    "yathreb.maaref",
    "jihene_abidi",
    "sarahhabibi653",
    "hajer.ayari",
    "jamel.halioui"
]

def get_users():
    users = []
    page = 1
    while True:
        url = f"{GITLAB_URL}/api/v4/users?per_page=100&page={page}"
        response = requests.get(url, headers=headers)
        if response.status_code != 200:
            print(f" Erreur API: {response.status_code}")
            break

        data = response.json()
        if not data:
            break

        users.extend(data)
        page += 1

    return users

def get_last_activity(user_id):
    url = f"{GITLAB_URL}/api/v4/users/{user_id}/events?per_page=1&sort=desc"
    response = requests.get(url, headers=headers)
    if response.status_code == 200:
        events = response.json()
        if events:
            return events[0]["created_at"]  # date ISO8601
    return None


def block_user(user_id, username):
    url = f"{GITLAB_URL}/api/v4/users/{user_id}/block"
    response = requests.post(url, headers=headers)
    if response.status_code == 201:
        print(f" Utilisateur '{username}' bloqué avec succès.")
    else:
        print(f" Erreur pour bloquer '{username}': {response.status_code}, {response.text}")


def main():
    users = get_users()
    for user in users:
        username = user.get("username")
        user_id = user.get("id")

        if username in EXCLUDED_USERS:
            print(f" Utilisateur '{username}' ignoré (exception définie).")
            continue

        last_activity = get_last_activity(user_id)

        if not last_activity:
            print(f" Utilisateur '{username}' sans activité connue → blocage.")
            block_user(user_id, username)
            continue

        last_activity_date = datetime.strptime(last_activity, "%Y-%m-%dT%H:%M:%S.%fZ")
        if last_activity_date < threshold_date:
            print(f" Utilisateur '{username}' inactif depuis {last_activity_date} → blocage.")
            block_user(user_id, username)
        else:
            print(f" Utilisateur '{username}' actif (dernière activité: {last_activity_date}).")

if __name__ == "__main__":
    main()
