import tkinter as tk
from tkinter import ttk
from tkinter import messagebox
from tkinter import scrolledtext
import openai
from wordpress_xmlrpc import Client, WordPressPost
from wordpress_xmlrpc.methods import posts
import requests
import urllib.parse
from pytube import YouTube
import json
import threading
import time
from bs4 import BeautifulSoup
import re
import sv_ttk  # Tema Sun Valley

# Configuración
openai_api_key = "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"
wordpress_url = "https://iaranda.es/xmlrpc.php"
wordpress_username = "admin"
wordpress_password = "8pE0 NscB KDEB 8rfy jyF8 KQUu"

# Categorías
CATEGORIAS = {
    'audio': 43,
    'imagen': 46,
    'otros': 47,
    'texto': 45,
    'video': 44
}

class ContentAggregator:
    def __init__(self):
        self.root = tk.Tk()
        self.root.title("Agregador de Contenido IA")
        
        # Inicializar timestamp para logging
        self.start_time = time.time()
        
        # Lista de IAs comunes para autocompletado
        self.ai_tags = [
            "ChatGPT", "GPT-3", "GPT-4", "Claude", "Claude 2", "Claude 3", "Claude Instant",
            "DALL-E", "DALL-E 2", "DALL-E 3", "Midjourney", "Stable Diffusion",
            "Gemini", "Gemini Pro", "Gemini Ultra", "PaLM", "Bard",
            "Anthropic", "OpenAI", "Google AI", "Microsoft Copilot",
            "Llama", "Llama 2", "Code Llama", "Mistral", "Mixtral",
            "Runway", "Leonardo AI", "Adobe Firefly",
            "AutoGPT", "Copilot", "GitHub Copilot",
            "Meta AI", "DeepMind", "HuggingFace"
        ]
        
        # Aplicar tema Sun Valley
        sv_ttk.set_theme("light")
        
        # Configurar ventana a pantalla completa
        screen_width = self.root.winfo_screenwidth()
        screen_height = self.root.winfo_screenheight()
        self.root.geometry(f"{screen_width}x{screen_height}")
        
        # Crear marco principal con padding
        self.main_frame = ttk.Frame(self.root, padding="20")
        self.main_frame.pack(fill=tk.BOTH, expand=True)
        
        # Columna izquierda (30% del ancho)
        self.left_frame = ttk.Frame(self.main_frame)
        self.left_frame.pack(side=tk.LEFT, fill=tk.BOTH, expand=False, padx=(0, 10), pady=0, ipadx=20)
        
        # Columna derecha (70% del ancho)
        self.right_frame = ttk.Frame(self.main_frame)
        self.right_frame.pack(side=tk.LEFT, fill=tk.BOTH, expand=True, padx=(10, 0), pady=0)
        
        # URL Frame con estilo moderno
        url_frame = ttk.LabelFrame(self.left_frame, text="URL del Contenido", padding="15")
        url_frame.pack(fill=tk.X, pady=(0, 15))
        
        self.url_entry = ttk.Entry(url_frame, font=('Segoe UI', 10))
        self.url_entry.pack(fill=tk.X, pady=(5, 0))
        
        # Categoría y Etiquetas Frame
        cat_tags_frame = ttk.LabelFrame(self.left_frame, text="Categoría y Etiquetas", padding="15")
        cat_tags_frame.pack(fill=tk.X, pady=(0, 15))
        
        # Categoría con estilo moderno
        ttk.Label(cat_tags_frame, text="Categoría:", font=('Segoe UI', 10)).pack(anchor=tk.W)
        self.category_var = tk.StringVar(value="Texto")
        category_combo = ttk.Combobox(cat_tags_frame, textvariable=self.category_var, font=('Segoe UI', 10))
        category_combo['values'] = ('Audio', 'Imagen', 'Otros', 'Texto', 'Video')
        category_combo.pack(fill=tk.X, pady=(5, 10))
        
        # Checkbox para InspirAcción
        self.inspiraccion_var = tk.BooleanVar(value=False)
        self.inspiraccion_check = ttk.Checkbutton(
            cat_tags_frame,
            text="InspirAcción (usar como título)",
            variable=self.inspiraccion_var,
            style='Switch.TCheckbutton'  # Estilo moderno tipo switch
        )
        self.inspiraccion_check.pack(fill=tk.X, pady=(0, 10))
        
        # Etiquetas con autocompletado
        ttk.Label(cat_tags_frame, text="Etiquetas de IA (separadas por comas):", font=('Segoe UI', 10)).pack(anchor=tk.W)
        self.tags_entry = ttk.Entry(cat_tags_frame, font=('Segoe UI', 10))
        self.tags_entry.pack(fill=tk.X, pady=(5, 0))
        
        # Lista de sugerencias
        self.suggestions_list = tk.Listbox(cat_tags_frame, font=('Segoe UI', 10), height=5)
        self.suggestions_list.pack(fill=tk.X, pady=(5, 0))
        self.suggestions_list.pack_forget()  # Inicialmente oculta
        
        # Vincular eventos para autocompletado
        self.tags_entry.bind('<KeyRelease>', self.update_suggestions)
        self.suggestions_list.bind('<<ListboxSelect>>', self.use_suggestion)
        
        # Vincular eventos para logging
        self.url_entry.bind('<KeyRelease>', self.on_url_change)
        self.tags_entry.bind('<KeyRelease>', self.on_tags_change)
        self.category_var.trace('w', self.on_category_change)
        self.inspiraccion_var.trace('w', self.on_inspiraccion_change)
        
        # Botones Frame con estilo moderno
        buttons_frame = ttk.Frame(self.left_frame)
        buttons_frame.pack(fill=tk.X, pady=(0, 15))
        
        self.process_button = ttk.Button(buttons_frame, text="Procesar", command=self.process_content_thread,
                                       style='Accent.TButton')
        self.process_button.pack(side=tk.LEFT, padx=(0, 5))
        
        self.publish_button = ttk.Button(buttons_frame, text="Publicar", command=self.publish_content,
                                       state='disabled')
        self.publish_button.pack(side=tk.LEFT)
        
        # Progress Frame
        progress_frame = ttk.Frame(self.left_frame)
        progress_frame.pack(fill=tk.X, pady=(0, 15))
        
        self.progress_var = tk.StringVar(value="")
        self.progress_label = ttk.Label(progress_frame, textvariable=self.progress_var, font=('Segoe UI', 10))
        self.progress_label.pack(fill=tk.X)
        
        # Log Frame (ahora en la izquierda)
        log_frame = ttk.LabelFrame(self.left_frame, text="Log", padding="15")
        log_frame.pack(fill=tk.BOTH, expand=True)
        
        self.log_text = scrolledtext.ScrolledText(
            log_frame,
            wrap=tk.WORD,
            height=10,
            font=('Cascadia Code', 9),
            bg='#f0f0f0',
            fg='#0078d4',
            insertbackground='#0078d4'
        )
        self.log_text.pack(fill=tk.BOTH, expand=True)
        
        self.log_message("Aplicación iniciada y lista para procesar contenido")
        
        # Preview Frame (ahora ocupa toda la columna derecha)
        preview_frame = ttk.LabelFrame(self.right_frame, text="Vista Previa", padding="15")
        preview_frame.pack(fill=tk.BOTH, expand=True)
        
        self.preview_text = scrolledtext.ScrolledText(
            preview_frame,
            wrap=tk.WORD,
            font=('Segoe UI', 10),
            bg='#ffffff',
            fg='#000000',
            insertbackground='#000000'
        )
        self.preview_text.pack(fill=tk.BOTH, expand=True)
        
        # Configurar estilos personalizados
        style = ttk.Style()
        style.configure('TLabelframe', padding=15)
        style.configure('TButton', padding=10, font=('Segoe UI', 10))
        style.configure('Accent.TButton', padding=10, font=('Segoe UI', 10, 'bold'))
        
        self.root.protocol("WM_DELETE_WINDOW", self.on_closing)
        self.root.mainloop()

    def update_suggestions(self, event=None):
        """Actualiza la lista de sugerencias basada en el texto actual"""
        text = self.tags_entry.get().split(',')[-1].strip().lower()
        
        if text:
            suggestions = [tag for tag in self.ai_tags if text in tag.lower()]
            if suggestions:
                self.suggestions_list.delete(0, tk.END)
                for s in suggestions:
                    self.suggestions_list.insert(tk.END, s)
                self.suggestions_list.pack(fill=tk.X, pady=(5, 0))
            else:
                self.suggestions_list.pack_forget()
        else:
            self.suggestions_list.pack_forget()

    def use_suggestion(self, event=None):
        """Usa la sugerencia seleccionada"""
        if self.suggestions_list.curselection():
            selected = self.suggestions_list.get(self.suggestions_list.curselection())
            current_tags = self.tags_entry.get().split(',')
            current_tags = [tag.strip() for tag in current_tags if tag.strip()]
            
            # Reemplazar la última etiqueta con la sugerencia
            if current_tags:
                current_tags = current_tags[:-1]
            current_tags.append(selected)
            
            # Actualizar el campo de etiquetas
            self.tags_entry.delete(0, tk.END)
            self.tags_entry.insert(0, ', '.join(current_tags))
            
            # Ocultar lista de sugerencias
            self.suggestions_list.pack_forget()

    def log_message(self, message):
        """Registra un mensaje en el log con timestamp"""
        timestamp = time.strftime('%H:%M:%S')
        elapsed = round(time.time() - self.start_time, 2)
        log_entry = f"[{timestamp}] ({elapsed}s) {message}\n"
        self.log_text.insert(tk.END, log_entry)
        self.log_text.see(tk.END)
        self.root.update_idletasks()

    def on_url_change(self, event):
        """Registra cambios en la URL"""
        url = self.url_entry.get().strip()
        if url:
            self.log_message(f"URL ingresada: {url}")

    def on_tags_change(self, event):
        """Registra cambios en las etiquetas"""
        tags = self.tags_entry.get().strip()
        if tags:
            self.log_message(f"Etiquetas modificadas: {tags}")

    def on_category_change(self, *args):
        """Registra cambios en la categoría"""
        category = self.category_var.get()
        self.log_message(f"Categoría seleccionada: {category}")

    def on_inspiraccion_change(self, *args):
        """Registra cambios en InspirAcción"""
        is_checked = self.inspiraccion_var.get()
        status = "activado" if is_checked else "desactivado"
        self.log_message(f"InspirAcción {status}")

    def reset_interface(self):
        """Reinicia la interfaz para un nuevo proceso"""
        self.log_message("Reiniciando interfaz para nuevo contenido...")
        
        # Limpiar campos
        self.url_entry.delete(0, tk.END)
        self.preview_text.delete(1.0, tk.END)
        self.tags_entry.delete(0, tk.END)
        
        # Resetear variables
        self.category_var.set("Texto")
        self.inspiraccion_var.set(False)
        self.progress_var.set("")
        
        # Resetear estados de botones
        self.process_button.state(['!disabled'])
        self.publish_button.state(['disabled'])
        
        # Actualizar UI
        self.root.update_idletasks()
        self.log_message("Listo para procesar nuevo contenido")

    def update_progress(self, message):
        """Actualiza el mensaje de progreso"""
        self.progress_var.set(message)
        self.root.update_idletasks()

    def process_content_thread(self):
        """Inicia el procesamiento en un hilo separado"""
        self.process_button.state(['disabled'])
        self.publish_button.state(['disabled'])
        self.update_progress("Procesando...")
        
        thread = threading.Thread(target=self.process_content)
        thread.daemon = True
        thread.start()

    def extract_youtube_info(self, url):
        """Extrae información de un video de YouTube"""
        try:
            self.log_message("Extrayendo información de YouTube...")
            
            # Extraer ID del video de YouTube
            video_id = None
            if 'youtube.com/watch?v=' in url:
                video_id = url.split('watch?v=')[1].split('&')[0]
            elif 'youtu.be/' in url:
                video_id = url.split('youtu.be/')[1].split('?')[0]
            
            if not video_id:
                raise ValueError("No se pudo extraer el ID del video")
            
            self.log_message(f"ID del video extraído: {video_id}")
            
            # Usar la API de YouTube Data v3 alternativa
            api_url = f"https://noembed.com/embed?url=https://www.youtube.com/watch?v={video_id}"
            response = requests.get(api_url)
            data = response.json()
            
            # Crear el código embebido con proporciones 16:9
            embed_code = f'''
            <div style="position: relative; width: 100%; height: 0; padding-bottom: 56.25%;">
                <iframe style="position: absolute; top: 0; left: 0; width: 100%; height: 100%;" 
                        src="https://www.youtube.com/embed/{video_id}" 
                        frameborder="0" 
                        allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" 
                        allowfullscreen>
                </iframe>
            </div>
            '''
            
            self.log_message("Información de YouTube extraída correctamente")
            
            return {
                'title': data.get('title', ''),
                'author': data.get('author_name', ''),
                'description': data.get('description', ''),
                'url': url,
                'embed_code': embed_code
            }
        except Exception as e:
            self.log_message(f"Error al procesar video de YouTube: {str(e)}")
            messagebox.showerror("Error", f"Error al procesar video de YouTube: {str(e)}")
            return None

    def extract_twitter_content(self, url):
        """Extrae contenido de un tweet"""
        try:
            self.log_message("Extrayendo información de Twitter/X...")
            
            # Obtener el código embebido de Twitter
            api_url = f"https://publish.twitter.com/oembed?url={url}"
            response = requests.get(api_url)
            data = response.json()
            
            self.log_message("Código embebido de Twitter obtenido")
            
            return {
                'content': data.get('html', ''),  # Usar el HTML embebido directamente
                'author': data.get('author_name', ''),
                'url': url,
                'embed_code': data.get('html', '')
            }
        except Exception as e:
            self.log_message(f"Error al procesar tweet: {str(e)}")
            messagebox.showerror("Error", f"Error al procesar tweet: {str(e)}")
            return None

    def extract_web_info(self, url):
        """Extrae información de una página web"""
        try:
            self.log_message("Extrayendo información de la página web...")
            
            headers = {
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
            }
            
            response = requests.get(url, headers=headers, timeout=10)
            response.raise_for_status()  # Lanzar excepción si hay error HTTP
            
            soup = BeautifulSoup(response.text, 'html.parser')
            
            # Intentar obtener el título
            title = soup.title.string if soup.title else ''
            
            # Intentar obtener el contenido principal
            content = ''
            article = soup.find('article') or soup.find('main') or soup.find('div', class_='content')
            if article:
                content = article.get_text(strip=True)
            else:
                # Si no encuentra contenido específico, tomar el texto del body
                content = soup.get_text(strip=True)
            
            return {
                'title': title,
                'content': content[:5000],  # Limitar el contenido a 5000 caracteres
                'url': url
            }
            
        except requests.RequestException as e:
            self.log_message(f"Error al acceder a la página web: {str(e)}")
            messagebox.showerror("Error", f"Error al acceder a la página web: {str(e)}")
            return None
        except Exception as e:
            self.log_message(f"Error al procesar la página web: {str(e)}")
            messagebox.showerror("Error", f"Error al procesar la página web: {str(e)}")
            return None

    def generate_title(self, content, tags):
        """Genera un título específico basado en el contenido y las etiquetas"""
        # Si InspirAcción está marcado, retornar ese título
        if self.inspiraccion_var.get():
            return "InspirAcción"
            
        prompt = f"""Genera un título ESPECÍFICO y DESCRIPTIVO para un artículo sobre IA.
        
        REGLAS IMPORTANTES:
        1. El título debe mencionar ESPECÍFICAMENTE la herramienta o IA sobre la que trata ({', '.join(tags)})
        2. Debe indicar claramente QUÉ HACE o PARA QUÉ SIRVE
        3. NO uses frases genéricas como "Revolución", "Innovación", "Transformación"
        4. NO uses "IA" o "Inteligencia Artificial" de forma genérica
        5. Máximo 60 caracteres
        6. Estilo: Tutorial/Guía/Análisis según corresponda
        
        Ejemplos BUENOS:
        - "Tutorial: Crear Voces Realistas con ElevenLabs XTTS"
        - "Guía Perplexity: Búsquedas Avanzadas para Estudiantes"
        - "Claude vs GPT-4: Comparativa en Programación Python"
        
        Ejemplos MALOS:
        - "Revolución en IA: Innovaciones que transforman el futuro"
        - "Inteligencia Artificial: Claves y Aplicaciones"
        
        Contenido del artículo:
        {content[:500]}
        
        Etiquetas: {', '.join(tags)}
        """

        try:
            response = openai.ChatCompletion.create(
                model="gpt-4",
                messages=[{
                    "role": "system",
                    "content": "Eres un experto en crear títulos específicos y descriptivos para artículos de tecnología."
                }, {
                    "role": "user",
                    "content": prompt
                }],
                temperature=0.7,
                max_tokens=60
            )
            title = response.choices[0].message['content'].strip()
            # Asegurar que no exceda 60 caracteres
            if len(title) > 60:
                title = title[:57] + "..."
            return title
        except Exception as e:
            self.update_progress(f"Error generando título: {str(e)}")
            return "Error generando título"

    def process_tweet(self, url):
        """Procesa un tweet y retorna su contenido embebido y descripción"""
        try:
            # Obtener ID del tweet de la URL
            tweet_id = url.split('/')[-1].split('?')[0]
            
            # URL de la API de oEmbed de Twitter
            oembed_url = f"https://publish.twitter.com/oembed?url={url}&omit_script=true"
            
            # Obtener el código de inserción
            response = requests.get(oembed_url)
            if response.status_code == 200:
                embed_data = response.json()
                embed_code = embed_data['html']
                
                # Generar descripción del tweet usando GPT
                tweet_content = embed_data.get('text', '')
                author = embed_data.get('author_name', '')
                
                # Añadir estilos para centrar y script de Twitter
                centered_embed = f"""
                <div style="display: flex; justify-content: center; align-items: center; width: 100%; margin: 20px 0;">
                    <div style="min-width: 350px; max-width: 550px;">
                        {embed_code}
                    </div>
                </div>
                <script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>
                """
                
                return {
                    'embed_code': centered_embed,
                    'content': tweet_content,
                    'author': author,
                    'type': 'tweet'
                }
            else:
                raise Exception(f"Error al obtener el tweet: {response.status_code}")
                
        except Exception as e:
            self.log_message(f"Error al procesar el tweet: {str(e)}")
            return None

    def process_content(self):
        """Procesa el contenido según la URL proporcionada"""
        try:
            self.log_message("Iniciando procesamiento de contenido...")
            url = self.url_entry.get().strip()
            if not url:
                self.log_message("Error: URL vacía")
                messagebox.showerror("Error", "Por favor, introduce una URL")
                return None
            
            self.log_message(f"Detectando tipo de contenido para: {url}")
            # Detectar tipo de contenido
            content_type = 'articulo'
            if 'twitter.com' in url or 'x.com' in url:
                content_type = 'tweet'
                self.log_message("Contenido detectado: Tweet")
                # Procesar tweet con centrado
                self.log_message("Procesando tweet...")
                tweet_info = self.process_tweet(url)
                if tweet_info:
                    self.log_message("Tweet procesado correctamente")
                    # Generar artículo descriptivo
                    self.log_message("Generando descripción del tweet...")
                    article_content = self.generate_article(tweet_info, 'tweet')
                    
                    # Combinar el artículo con el tweet embebido centrado
                    full_content = f"{article_content}\n\n{tweet_info['embed_code']}"
                    
                    self.preview_text.delete(1.0, tk.END)
                    self.preview_text.insert(tk.END, full_content)
                    self.category_var.set('Texto')
                    self.publish_button.state(['!disabled'])
                    self.log_message("Tweet y descripción listos para publicar")
                    return tweet_info
            
            elif 'youtube.com' in url or 'youtu.be' in url:
                content_type = 'youtube'
                self.log_message("Contenido detectado: Video de YouTube")
                # Procesar YouTube
                self.log_message("Procesando video...")
                video_info = self.extract_youtube_info(url)
                if video_info:
                    self.log_message("Video procesado correctamente")
                    self.log_message("Generando descripción del video...")
                    article_content = self.generate_article(video_info, 'youtube')
                    self.preview_text.delete(1.0, tk.END)
                    self.preview_text.insert(tk.END, article_content)
                    self.category_var.set('Video')
                    self.publish_button.state(['!disabled'])
                    self.log_message("Video y descripción listos para publicar")
                    return video_info
            else:
                self.log_message("Contenido detectado: Artículo web")
                # Procesar artículo web
                self.log_message("Procesando página web...")
                article_info = self.extract_web_info(url)
                if article_info:
                    self.log_message("Página web procesada correctamente")
                    self.log_message("Generando artículo...")
                    article_content = self.generate_article(article_info, 'articulo')
                    self.preview_text.delete(1.0, tk.END)
                    self.preview_text.insert(tk.END, article_content)
                    self.category_var.set('Texto')
                    self.publish_button.state(['!disabled'])
                    self.log_message("Artículo listo para publicar")
                    return article_info
            
            return None
            
        except Exception as e:
            self.log_message(f"Error al procesar el contenido: {str(e)}")
            messagebox.showerror("Error", f"Error al procesar el contenido: {str(e)}")
            return None

    def generate_article(self, content_info, content_type):
        """Genera un artículo usando GPT"""
        try:
            self.log_message("Generando artículo con IA...")
            
            if content_type == 'youtube':
                system_prompt = """
                Eres un experto en tecnología y educación. Escribe un artículo en español sobre el video proporcionado.
                El artículo debe ser informativo, profesional y educativo.
                Céntrate en explicar los conceptos clave y su utilidad práctica.
                """
                
                prompt = f"""
                Escribe un artículo informativo basado en este video:
                Título: {content_info.get('title', '')}
                Autor: {content_info.get('author', '')}
                Descripción: {content_info.get('description', '')}
                
                El artículo debe:
                1. Explicar los conceptos principales
                2. Destacar los puntos clave de aprendizaje
                3. Ser claro y educativo
                4. Tener entre 200-300 palabras
                
                NO incluyas el título ni la URL en el texto.
                NO uses llamadas a la acción ni pidas comentarios.
                """
                
                article = openai.ChatCompletion.create(
                    model="gpt-4",
                    messages=[
                        {"role": "system", "content": system_prompt},
                        {"role": "user", "content": prompt}
                    ],
                    max_tokens=1000,
                    temperature=0.7
                )
                
                return article.choices[0].message['content'].strip()
                
            elif content_type == 'tweet':
                system_prompt = """
                Eres un experto en tecnología y educación. Escribe un artículo en español sobre el contenido del tweet.
                El artículo debe ser informativo, profesional y educativo.
                Céntrate en explicar los conceptos clave y su utilidad práctica.
                """
                
                prompt = f"""
                Escribe un artículo informativo basado en este tweet:
                Contenido: {content_info.get('content', '')}
                Autor: {content_info.get('author', '')}
                
                El artículo debe:
                1. Explicar el contexto y relevancia
                2. Destacar los puntos importantes
                3. Ser claro y educativo
                4. Tener entre 150-200 palabras
                
                NO incluyas el título ni la URL en el texto.
                NO uses llamadas a la acción ni pidas comentarios.
                """
                
                article = openai.ChatCompletion.create(
                    model="gpt-4",
                    messages=[
                        {"role": "system", "content": system_prompt},
                        {"role": "user", "content": prompt}
                    ],
                    max_tokens=1000,
                    temperature=0.7
                )
                
                return article.choices[0].message['content'].strip()
                
            else:
                system_prompt = """
                Eres un experto en tecnología y educación. Escribe un artículo en español sobre el contenido proporcionado.
                El artículo debe ser informativo, profesional y educativo.
                Céntrate en explicar los conceptos clave y su utilidad práctica.
                """
                
                prompt = f"""
                Escribe un artículo informativo basado en este contenido:
                {content_info.get('content', '')[:1500]}
                
                El artículo debe:
                1. Explicar los conceptos principales
                2. Destacar los puntos clave
                3. Ser claro y educativo
                4. Tener entre 200-300 palabras
                
                NO incluyas el título ni la URL en el texto.
                NO uses llamadas a la acción ni pidas comentarios.
                """
                
                article = openai.ChatCompletion.create(
                    model="gpt-4",
                    messages=[
                        {"role": "system", "content": system_prompt},
                        {"role": "user", "content": prompt}
                    ],
                    max_tokens=1000,
                    temperature=0.7
                )
                
                return article.choices[0].message['content'].strip()
                
        except Exception as e:
            self.log_message(f"Error al generar el artículo: {str(e)}")
            messagebox.showerror("Error", f"Error al generar el artículo: {str(e)}")
            return None

    def publish_content(self):
        """Publica el contenido en WordPress"""
        try:
            self.log_message("Iniciando proceso de publicación...")
            url = self.url_entry.get().strip()
            if not url:
                self.log_message("Error: URL vacía")
                messagebox.showerror("Error", "Por favor, introduce una URL")
                return
            
            # Obtener etiquetas actuales
            tags = [tag.strip() for tag in self.tags_entry.get().split(',') if tag.strip()]
            self.log_message(f"Etiquetas a usar: {', '.join(tags)}")
            
            # Verificar si es InspirAcción
            if self.inspiraccion_var.get():
                self.log_message("Modo InspirAcción activado")
                title = "InspirAcción"
                if "InspirAcción" not in tags:
                    tags.append("InspirAcción")
                    self.log_message("Etiqueta InspirAcción añadida automáticamente")
                    self.tags_entry.delete(0, tk.END)
                    self.tags_entry.insert(0, ", ".join(tags))
            else:
                self.log_message("Generando título...")
                content_info = {'url': url, 'content': self.preview_text.get(1.0, tk.END)}
                title = self.generate_title(content_info['content'], tags)
                self.log_message(f"Título generado: {title}")
            
            self.log_message("Preparando post para WordPress...")
            # Crear post
            post = WordPressPost()
            post.title = title
            post.content = self.preview_text.get(1.0, tk.END)
            
            # Categoría
            category = self.category_var.get()
            self.log_message(f"Asignando categoría: {category}")
            post.terms_names = {
                'category': [category]
            }
            
            # Añadir etiquetas
            if tags:
                self.log_message(f"Asignando etiquetas: {', '.join(tags)}")
                post.terms_names['post_tag'] = tags
            
            post.post_status = 'publish'
            
            # Crear cliente WordPress
            self.log_message("Conectando con WordPress...")
            wp = Client(wordpress_url, wordpress_username, wordpress_password)
            
            # Publicar
            self.log_message("Publicando contenido...")
            wp.call(posts.NewPost(post))
            self.log_message("¡Contenido publicado exitosamente!")
            messagebox.showinfo("Éxito", "Contenido publicado correctamente")
            
            # Reiniciar interfaz para nuevo contenido
            self.reset_interface()
            
        except Exception as e:
            error_msg = f"Error al publicar: {str(e)}"
            self.log_message(error_msg)
            messagebox.showerror("Error", error_msg)
        finally:
            self.publish_button.state(['!disabled'])

    def on_closing(self):
        self.root.destroy()

def main():
    app = ContentAggregator()


if __name__ == "__main__":
    main()
