import logging
from datetime import datetime, date
from typing import List, Dict, Any, Optional
import sys

sys.path.append('/var/www/html/config')

from cnxpdo import get_connection

def obtener_noticias(fecha_noticia: Optional[str]) -> Dict[str, Any]:
    conexion = None
    cursor = None

    try:
        conexion = get_connection()
        if not conexion:
            raise Exception("No se pudo establecer conexión a la base de datos")

        # Validación de la fecha
        if fecha_noticia:
            try:
                datetime.strptime(fecha_noticia, "%Y-%m-%d")
            except ValueError:
                raise ValueError("Formato de fecha inválido. Use YYYY-MM-DD")

        # Construcción del query
        query = "SELECT * FROM noticias WHERE id_estado = 1"
        params = []

        if fecha_noticia:
            query += " AND DATE(fecha_noticia) = STR_TO_DATE(%s, '%%Y-%%m-%%d')"
            params.append(fecha_noticia)

        # Ordenar por fecha descendente y limitar a los últimos 6 registros
        query += " ORDER BY fecha_publicacion DESC LIMIT 7"

        # Ejecutar consulta
        cursor = conexion.cursor(dictionary=True)
        cursor.execute(query, params)
        datos = cursor.fetchall()

        # Formatear fecha como string
        for noticia in datos:
            if isinstance(noticia["fecha_noticia"], (datetime, date)):
                noticia["fecha_noticia"] = noticia["fecha_noticia"].strftime("%Y-%m-%d")

        return {
            "datos": datos
        }

    except Exception as e:
        logging.error(f"[ERROR] en obtener_noticias: {str(e)}")
        raise
    finally:
        if cursor:
            cursor.close()
        if conexion:
            conexion.close()