import requests
import json
from datetime import datetime
import os

API_URL = "https://live.feelfm.fr/api/nowplaying/feel-lsud"
COVER_EXCEPTIONS_URL = "https://replay.feelfm.fr/newapi/cover_exceptions.json"
FALLBACK_COVER = "https://live.feelfm.fr/static/uploads/feel-lsud/album_art.1746281901.png"

OUTPUT_PATH = "/var/www/html/newapi/currentLSUD.json"

# Fonction de log avec horodatage
def log(message):
    timestamp = datetime.now().strftime("[%d/%m/%Y %H:%M:%S]")
    print(f"{timestamp} {message}")

# Charger les exceptions depuis URL distante
def fetch_cover_exceptions():
    try:
        response = requests.get(COVER_EXCEPTIONS_URL)
        if response.status_code == 200:
            return response.json()
        else:
            log(f"Erreur lors du chargement des exceptions ({response.status_code})")
            return []
    except Exception as e:
        log(f"Exception lors du chargement des exceptions : {e}")
        return []

# Vérifier si une pochette personnalisée existe
def get_cover_from_exceptions(title, artist, exceptions):
    for exception in exceptions:
        if exception["titre"].lower() == title.lower() and exception["artiste"].lower() == artist.lower():
            return exception["cover_url"]
    return None

# Rechercher la pochette sur iTunes
def get_cover_url(title, artist):
    try:
        search_url = f"https://itunes.apple.com/search?term={title}-{artist}&limit=1"
        response = requests.get(search_url)
        response.raise_for_status()
        data = response.json()
        if data['resultCount'] > 0:
            return data['results'][0]['artworkUrl100'].replace("100x100bb.jpg", "500x500bb.jpg")
        else:
            return FALLBACK_COVER
    except Exception as e:
        log(f"Erreur iTunes : {e}")
        return FALLBACK_COVER

# Obtenir le titre actuel
try:
    response = requests.get(API_URL)
    if response.ok:
        data = response.json()
        titre = data["now_playing"]["song"]["title"]
        artiste = data["now_playing"]["song"]["artist"]
        timestamp = data["now_playing"]["played_at"]

        log(f"Titre en cours : {titre}")
        log(f"Artiste       : {artiste}")

        # Charger exceptions
        exceptions = fetch_cover_exceptions()

        # Chercher la pochette
        cover_url = get_cover_from_exceptions(titre, artiste, exceptions) or get_cover_url(titre, artiste)

        log(f"Pochette      : {cover_url}")

        # Préparer les données à enregistrer
        current_data = {
            "timestamp": timestamp,
            "titre": titre,
            "artiste": artiste,
            "cover_url": cover_url
        }

        # Écrire dans le fichier JSON (en écrasant l'ancien)
        with open(OUTPUT_PATH, "w", encoding="utf-8") as f:
            json.dump(current_data, f, indent=2, ensure_ascii=False)

        log(f"Fichier mis à jour : {OUTPUT_PATH}")

    else:
        log(f"Erreur API AzuraCast : {response.status_code}")
except Exception as e:
    log(f"Erreur de récupération des données : {e}")
