import os
import requests
import sys
import json
from datetime import datetime, timezone
from dateutil.parser import parse

VAULT_ADDR = "https://vault.allence.cloud"
VAULT_TOKEN = os.getenv("VAULT_TOKEN")
DISCORD_WEBHOOK_URL = "https://discord.com/api/webhooks/1409523158637084722/fsb1MO4KwECrv4XakaVhZJmQ1YI4HXS4jprHEvkfqtWVNI-V4sX_tecP8EOChwd12dP7"


def send_discord_notification(message):
    if not DISCORD_WEBHOOK_URL:
        print("Erreur: DISCORD_WEBHOOK_URL n'est pas configuré. Notification annulée.")
        return

    payload = {
        "content": message
    }

    try:
        response = requests.post(
            DISCORD_WEBHOOK_URL,
            headers={'Content-Type': 'application/json'},
            data=json.dumps(payload),
            timeout=10
        )
        response.raise_for_status() #
        print("-> Notification Discord envoyée avec succès.")
    except requests.exceptions.RequestException as e:
        print(f"Erreur lors de l'envoi de la notification Discord: {e}")

def get_vault_token_expiry(vault_addr, vault_token):
    """Récupère la date d'expiration du jeton Vault."""
    if not vault_addr or not vault_token:
        print("Erreur: VAULT_ADDR ou VAULT_TOKEN n'est pas configuré.")
        sys.exit(1)

    url = f"{vault_addr}/v1/auth/token/lookup-self"
    headers = {"X-Vault-Token": vault_token}

    try:
        response = requests.get(url, headers=headers, timeout=10)


        if response.status_code != 200:
            error_msg = f"Échec de la vérification Vault. Code HTTP: {response.status_code}."
            return None, None, error_msg

        data = response.json().get('data', {})
        expiry_time_str = data.get('expire_time')

        if not expiry_time_str or expiry_time_str == "null":
            return None, None, "Le jeton n'a pas de date d'expiration (Root/Périodique)."

        expiry_time = parse(expiry_time_str)
        now = datetime.now(timezone.utc)
        time_left = expiry_time - now

        return expiry_time, time_left, None

    except requests.exceptions.RequestException as e:
        return None, None, f"Erreur de connexion à Vault: {e}"
    except Exception as e:
        return None, None, f"Erreur inattendue lors du traitement de la réponse Vault: {e}"

def main():

    expiry_time, time_left, error = get_vault_token_expiry(VAULT_ADDR, VAULT_TOKEN)

    if error:
        print(f"Statut critique Vault: {error}")
        critical_message = f"❌ **ALERTE CRITIQUE VAULT** ❌\nLe token CI/CD pour  est injoignable ou invalide!\nCause: {error}"
        send_discord_notification(critical_message)
        return


    days_left = time_left.days
    expiry_date_str = expiry_time.strftime('%Y-%m-%d %H:%M:%S UTC')

    print(f"Date d'Expiration (UTC): {expiry_date_str}")
    print(f"Jours restants: {days_left}")



    if days_left == 3 or days_left == 2 or days_left == 1:

        if days_left == 1:
            alert_icon = "🚨"
        else:
            alert_icon = "⚠️"

        alert_message = (
            f"{alert_icon} **ALERTE Vault Token Expiration** {alert_icon}\n"
            f"Le token Vault CI/CD  va expirer dans **{days_left} jour(s)** !\n"
            f"**Date d'expiration :** {expiry_date_str}\n"
            f"**Action requise :** Veuillez renouveler le jeton Vault (VAULT_CI_TOKEN) immédiatement."
        )
        send_discord_notification(alert_message)

    elif days_left <= 0:

        critical_message = (
            f"❌ **ALERTE CRITIQUE Vault Token Expiré** ❌\n"
            f"Le token CI/CD  a **expiré** le {expiry_date_str}. Les pipelines vont échouer !\n"
            f"**Action :** Le jeton doit être renouvelé et mis à jour."
        )
        send_discord_notification(critical_message)

    else:
        print("✅ Le jeton Vault est valide pour plus de 3 jours. Aucune alerte envoyée.")


if __name__ == "__main__":
    try:
        from dateutil.parser import parse
    except ImportError:
        print("Erreur : La librairie 'python-dateutil' est requise. Installez-la avec : pip install python-dateutil requests")
        sys.exit(1)

    main()
