import requests
import json
from datetime import datetime, timedelta
import os
import shutil

API_URL = "https://live.feelfm.fr/api/nowplaying/oxaz"
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"
HISTORY_FOLDER = "/var/www/html/newapi/recent/oxaz"
LAST_CLEANUP_FILE = os.path.join(HISTORY_FOLDER, "last_cleanup.txt")

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

# Supprimer les dossiers de plus de 365 jours
def cleanup_old_folders(base_folder, days=365):
    cutoff_date = datetime.now() - timedelta(days=days)
    for folder in os.listdir(base_folder):
        folder_path = os.path.join(base_folder, folder)
        if os.path.isdir(folder_path):
            try:
                folder_date = datetime.strptime(folder, "%Y-%m-%d")
                if folder_date < cutoff_date:
                    shutil.rmtree(folder_path)
                    log(f"Dossier supprimé : {folder_path}")
            except ValueError:
                # Ignore les dossiers qui ne respectent pas le format YYYY-MM-DD
                pass

# Vérifier si on doit lancer le nettoyage (1 fois par jour max)
def daily_cleanup(base_folder, days=365):
    today = datetime.now().strftime("%Y-%m-%d")
    last_cleanup_date = None

    if os.path.exists(LAST_CLEANUP_FILE):
        with open(LAST_CLEANUP_FILE, "r", encoding="utf-8") as f:
            last_cleanup_date = f.read().strip()

    if last_cleanup_date != today:
        log("Nettoyage quotidien lancé...")
        cleanup_old_folders(base_folder, days)
        with open(LAST_CLEANUP_FILE, "w", encoding="utf-8") as f:
            f.write(today)
    else:
        log("Nettoyage déjà effectué aujourd'hui, on saute.")

# Charger les exceptions de couverture depuis l'URL
def fetch_cover_exceptions():
    try:
        response = requests.get(COVER_EXCEPTIONS_URL)
        if response.status_code == 200:
            log("Exceptions de pochette chargées avec succès.")
            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 []

# Chercher une pochette dans les exceptions
def get_cover_from_exceptions(title, artist, exceptions):
    for exception in exceptions:
        if exception["titre"].lower() == title.lower() and exception["artiste"].lower() == artist.lower():
            log(f"Pochette trouvée dans les exceptions pour : {title} - {artist}")
            return exception["cover_url"]
    return None

# Récupérer une pochette via 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:
            artwork_url = data['results'][0]['artworkUrl100']
            artwork_url = artwork_url.replace("100x100bb.jpg", "500x500bb.jpg")
            log(f"Pochette récupérée via iTunes pour : {title} - {artist}")
            return artwork_url
        else:
            log(f"Aucun résultat iTunes pour : {title} - {artist}")
            return FALLBACK_COVER
    except Exception as e:
        log(f"Erreur iTunes pour {title} - {artist} : {e}")
        return FALLBACK_COVER

# Récupérer les données depuis AzuraCast
response = requests.get(API_URL)
if response.ok:
    data = response.json()
    titre = data["now_playing"]["song"]["title"]
    artiste = data["now_playing"]["song"]["artist"]
    timestamp_val = data["now_playing"]["played_at"]

    log(f"Titre actuel : {titre} - {artiste} (timestamp : {timestamp_val})")

    # Charger les exceptions
    cover_exceptions = fetch_cover_exceptions()

    # Trouver la bonne pochette
    cover_url = get_cover_from_exceptions(titre, artiste, cover_exceptions)
    if not cover_url:
        cover_url = get_cover_url(titre, artiste)

    entree = {
        "timestamp": timestamp_val,
        "titre": titre,
        "artiste": artiste,
        "cover_url": cover_url
    }

    # Déterminer le sous-dossier du jour et le fichier JSON de l’heure courante
    current_datetime = datetime.now()
    date_folder = current_datetime.strftime("%Y-%m-%d")   # ex: 2025-09-20
    daily_folder = os.path.join(HISTORY_FOLDER, date_folder)
    filename = current_datetime.strftime("%H.json")       # ex: 14.json
    filepath = os.path.join(daily_folder, filename)

    # S'assurer que le dossier existe
    os.makedirs(daily_folder, exist_ok=True)

    # Nettoyer les anciens dossiers (1 fois par jour max)
    daily_cleanup(HISTORY_FOLDER, days=365)

    # Charger l'historique existant
    try:
        with open(filepath, "r", encoding="utf-8") as f:
            historique = json.load(f)
    except FileNotFoundError:
        log(f"Fichier {filename} introuvable, création d'un nouveau.")
        historique = []
    except json.JSONDecodeError:
        log(f"Erreur de lecture du fichier {filename}, fichier réinitialisé.")
        historique = []

    # Vérification de duplication
    if historique and historique[0]["titre"] == titre and historique[0]["artiste"] == artiste:
        log("La chanson est déjà en position 0, pas besoin de l'ajouter.")
    else:
        historique.insert(0, entree)
        with open(filepath, "w", encoding="utf-8") as f:
            json.dump(historique, f, indent=2, ensure_ascii=False)
        log(f"Ajouté au fichier {filename} : {titre} - {artiste}")

else:
    log(f"Erreur de récupération depuis AzuraCast : {response.status_code}")
