import os
from datetime import datetime


class Logger:
    def __init__(self, log_file_path: str):
        self.log_file = log_file_path
        self._init_log_file()

    def _init_log_file(self):
        """Initialize log file if it doesn't exist"""
        log_dir = os.path.dirname(self.log_file)
        if not os.path.exists(log_dir):
            os.makedirs(log_dir)
        if not os.path.exists(self.log_file):
            try:
                with open(self.log_file, "w", encoding="utf-8") as f:
                    f.write("")
            except Exception as e:
                print(f"Error initializing log file {self.log_file}: {e}")

    def append_log(self, message: str) -> None:
        """Append a message to the log file with timestamp."""
        try:
            timestamp = datetime.now().strftime("[%H:%M:%S] ")
            lines = message.split("\n")
            lines_with_timestamp = [
                f"{timestamp}{line}\n" for line in lines if line.strip()
            ]

            if lines_with_timestamp:
                with open(self.log_file, "a", encoding="utf-8") as f:
                    f.writelines(lines_with_timestamp)
        except Exception as e:
            print(f"Error writing to log file {self.log_file}: {e}")

    def read_log(self) -> str:
        """Read the entire log file"""
        try:
            with open(self.log_file, "r", encoding="utf-8") as f:
                return f.read()
        except Exception as e:
            print(f"Error reading log file {self.log_file}: {e}")
            return ""

    def clear_log(self) -> bool:
        """Clear the log file"""
        try:
            with open(self.log_file, "w", encoding="utf-8") as f:
                f.write("")
            return True
        except Exception as e:
            print(f"Error clearing log file {self.log_file}: {e}")
            return False
