import os
from datetime import datetime
from typing import TextIO, Optional

class Colors:
    GREEN = "\033[92m"
    RED = "\033[91m"
    RESET = "\033[0m"

class Logger:
    """Simple logger class with debug and error methods using separate files"""
    
    def __init__(self, log_dir: str, debug: bool = False) -> None:
        self.log_dir: str = log_dir
        self.debug: bool = debug
        self.timestamp: str = self._get_timestamp()
        
        ## Create logging directory ## 
        os.makedirs(log_dir, exist_ok=True)
        
        ## Initialize file streams ##
        log_filename: str = f"llm_modulo_{self.timestamp}.log"
        error_filename: str = f"llm_modulo_{self.timestamp}.error"
        
        log_filepath: str = os.path.join(self.log_dir, log_filename)
        error_filepath: str = os.path.join(self.log_dir, error_filename)
        
        self.log_file: TextIO = open(log_filepath, "w", encoding="utf-8")
        self.error_file: TextIO = open(error_filepath, "w", encoding="utf-8")

    def __del__(self) -> None:
        self.log_file.close()
        self.error_file.close()
    
    def _get_timestamp(self) -> str:
        return datetime.now().strftime("%Y%m%d_%H%M%S")
    
    def _write_to_stream(self, file_obj: TextIO, message: str) -> None:
        timestamp: str = self._get_timestamp()
        file_obj.write(f"[{timestamp}] {message}\n")
        file_obj.flush() 
    
    def info(self, message: str) -> None:
        self._write_to_stream(self.log_file, f"{Colors.GREEN}[INFO]{Colors.RESET} {message}")
        if self.debug:
            print(f"{Colors.GREEN}[INFO]{Colors.RESET} {message}")
    
    def error(self, message: str) -> None:
        self._write_to_stream(self.error_file, f"{Colors.RED}[ERROR]{Colors.RESET} {message}")
        print(f"{Colors.RED}[ERROR]{Colors.RESET} {message}")