import logging
import os
import time
import requests
from typing import Dict, Any
from dotenv import load_dotenv

# ========== CONFIGURACIÓN DE RUTAS PARA VARIABLES DE ENTORNO ==========
script_dir = os.path.dirname(os.path.abspath(__file__))
landing_dir = os.path.dirname(script_dir)
root_dir = os.path.dirname(landing_dir)
env_path = os.path.join(root_dir, "crm", "configuraciones", ".env")

if os.path.exists(env_path):
    load_dotenv(env_path)
    logging.info(f"Variables de entorno cargadas desde: {env_path}")
else:
    logging.warning(f"No se encontró el archivo .env en: {env_path}")

X_TOKEN = os.getenv('X_TOKEN')

cache_data = {
    'tweets': None,
    'timestamp': 0
}

CACHE_DURATION = 14 * 60

# Verifica si el caché actual sigue siendo válido
def is_cache_valid() -> bool:
    current_time = time.time()
    cache_age = current_time - cache_data['timestamp']
    
    return (cache_data['tweets'] is not None and 
            cache_age < CACHE_DURATION)

# Calcula la edad del caché en minutos
def get_cache_age_minutes() -> float:
    return (time.time() - cache_data['timestamp']) / 60

def obtener_tweets(user_id: str, max_results: int = 5) -> Dict[str, Any]:

    # REVISAR CACHE PRIMERO
    if is_cache_valid():
        cache_age = get_cache_age_minutes()
        logging.info(f"📦 Usando caché (edad: {cache_age:.1f} min)")
        return cache_data['tweets']
    
    # NO HAY CACHE VALIDO - PEDIR A TWITTER
    logging.info(f"🔄 Obteniendo tweets frescos para {user_id}")

    if not X_TOKEN:
        raise Exception("X_TOKEN no está configurado")

    try:
        headers = {"Authorization": f"Bearer {X_TOKEN}"}
        
        # Una sola petición directa usando el user_id
        tweets_url = f"https://api.twitter.com/2/users/{user_id}/tweets"
        params = {
            "max_results": max_results,
            "media.fields": "url,preview_image_url,type,width,height",
            "expansions": "attachments.media_keys"
        }
        
        tweets_response = requests.get(tweets_url, headers=headers, params=params, timeout=10)
        
        # Manejo de errores
        if tweets_response.status_code == 429:
            raise Exception("⏰ Límite de Twitter alcanzado. Espera 15 minutos antes de la próxima prueba.")
        
        if tweets_response.status_code == 401:
            raise Exception("🔑 Token de Twitter inválido o expirado")
        
        if tweets_response.status_code == 404:
            raise Exception(f"👤 Usuario con ID {user_id} no encontrado")
            
        if tweets_response.status_code != 200:
            raise Exception(f"❌ Error obteniendo tweets: HTTP {tweets_response.status_code}")

        # Procesar respuesta
        tweets_data = tweets_response.json()
        all_tweets = tweets_data.get("data", [])
        
        if not all_tweets:
            raise Exception(f"📭 Usuario {user_id} no tiene tweets disponibles")
        
        result = {
            "datos": all_tweets, 
            "includes": tweets_data.get("includes")
        }

        cache_data['tweets'] = result
        cache_data['timestamp'] = time.time()
        
        logging.info(f"✅ {len(all_tweets)} tweets obtenidos para usuario {user_id}")
        return {"datos": all_tweets, "includes": tweets_data.get("includes")}
            
    except requests.exceptions.Timeout:
        raise Exception("⏱️ Timeout conectando con Twitter (10 segundos)")
    except requests.exceptions.RequestException as e:
        raise Exception(f"🌐 Error de conexión: {str(e)}")
    except Exception as e:
        logging.error(f"Error en obtener_tweets: {str(e)}")
        raise