"""Logger for TgrEzLi: ezlog for console, optional file append when save_log_file is True."""
from __future__ import annotations

from datetime import datetime

from ezlog import EzLog

from TgrEzLi.defaults import DEFAULT_LOG_FILE_PATH


def _format_msg(msg: str, *args: object) -> str:
    return msg % args if args else msg


class TgrezliLogger:
    """Adapter: EzLog for console output and optional file append (save_log_file)."""

    def __init__(
        self,
        save_log_file: bool = False,
        log_file_path: str | None = DEFAULT_LOG_FILE_PATH,
    ) -> None:
        self._ez = EzLog()
        self._save_log_file = save_log_file
        self._log_file_path = log_file_path or DEFAULT_LOG_FILE_PATH

    def set_save_log_file(self, flag: bool) -> None:
        """Enable or disable writing log lines to the file."""
        self._save_log_file = flag

    def _write_file(self, level: str, msg: str) -> None:
        if not self._save_log_file or not self._log_file_path:
            return
        try:
            line = f"[{datetime.now():%Y-%m-%d %H:%M:%S}] [{level}] TgrEzLi - {msg}\n"
            with open(self._log_file_path, "a", encoding="utf-8") as f:
                f.write(line)
        except OSError:
            pass

    def info(self, msg: str, *args: object) -> None:
        formatted = _format_msg(msg, *args)
        self._ez.info(formatted)
        self._write_file("INFO", formatted)

    def debug(self, msg: str, *args: object) -> None:
        formatted = _format_msg(msg, *args)
        self._ez.d(formatted)
        self._write_file("DEBUG", formatted)

    def error(self, msg: str, *args: object) -> None:
        formatted = _format_msg(msg, *args)
        self._ez.error(formatted)
        self._write_file("ERROR", formatted)


def get_default_logger(
    save_log_file: bool = False,
    log_file_path: str | None = DEFAULT_LOG_FILE_PATH,
) -> TgrezliLogger:
    """Return a logger that uses ezlog for console and optionally appends to a file."""
    return TgrezliLogger(save_log_file=save_log_file, log_file_path=log_file_path or DEFAULT_LOG_FILE_PATH)


__all__ = ["TgrezliLogger", "get_default_logger"]
