# utils/logging_manager.py
import logging
import os
from typing import Optional
from datetime import datetime
import tkinter as tk
from queue import Queue, Empty
from .output_redirector import OutputRedirector

class LoggingManager:
    def __init__(self, work_dir: str):
        self.work_dir = work_dir
        self.log_dir = os.path.join(work_dir, "logs")
        os.makedirs(self.log_dir, exist_ok=True)
        
        self.logger = self._setup_logger()
        self.queue: Optional[Queue] = None
        self.text_widget: Optional[tk.Text] = None
        
    def _setup_logger(self) -> logging.Logger:
        logger = logging.getLogger("app_logger")
        logger.setLevel(logging.INFO)
        
        # File handler
        log_file = os.path.join(self.log_dir, f"app_{datetime.now():%Y%m%d}.log")
        file_handler = logging.FileHandler(log_file, encoding="utf-8")
        file_handler.setLevel(logging.INFO)
        
        formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(message)s")
        file_handler.setFormatter(formatter)
        
        logger.addHandler(file_handler)
        return logger
        
    def setup_gui_logging(self, text_widget: tk.Text, queue: Queue):
        """Setup logging to GUI text widget"""
        self.text_widget = text_widget
        self.queue = queue
        
        # Add handler for GUI logging
        gui_handler = logging.StreamHandler(OutputRedirector(queue))
        gui_handler.setLevel(logging.INFO)
        formatter = logging.Formatter("%(message)s")
        gui_handler.setFormatter(formatter)
        
        self.logger.addHandler(gui_handler)
        
    def process_log_queue(self):
        """Process pending log messages"""
        if self.queue and self.text_widget:
            while True:
                try:
                    message = self.queue.get_nowait()
                    self.text_widget.insert(tk.END, message)
                    self.text_widget.see(tk.END)
                    self.text_widget.update_idletasks()
                except Empty:
                    break
                    
    def clear_output(self):
        """Clear the text widget"""
        if self.text_widget:
            self.text_widget.delete("1.0", tk.END)
            self.text_widget.update_idletasks()