# Copyright 2026 Espressif Systems (Shanghai) Co., Ltd.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import logging
import os
import sys
from logging.handlers import RotatingFileHandler


def setup_logger(name: str = "esp_viewer", debug_mode: bool = False) -> logging.Logger:
    """
    Initialize and return the root logger for the application.
    Writes DEBUG logs to logs/esp_viewer.log. If debug_mode is True, console
    also gets DEBUG logs, otherwise INFO logs.
    """
    logger = logging.getLogger(name)

    # Check if we've already configured handlers
    if logger.handlers:
        return logger

    logger.setLevel(logging.DEBUG)

    # Ensure logs directory exists
    os.makedirs("logs", exist_ok=True)

    # Rotating File Handler (Max 5MB per file, keep 3 old files)
    file_handler = RotatingFileHandler(
        "logs/esp_viewer.log", maxBytes=5 * 1024 * 1024, backupCount=3, encoding="utf-8"
    )
    file_handler.setLevel(logging.DEBUG)

    # Formatter for file (Detailed)
    file_formatter = logging.Formatter(
        "%(asctime)s - %(name)s - %(levelname)s - [%(filename)s:%(lineno)d] - %(message)s"
    )
    file_handler.setFormatter(file_formatter)

    # Console Handler
    console_handler = logging.StreamHandler(sys.stdout)
    if debug_mode or os.environ.get("ESP_VIEWER_DEBUG") == "1":
        console_handler.setLevel(logging.DEBUG)
    else:
        console_handler.setLevel(logging.INFO)

    # Formatter for console (Clean)
    console_formatter = logging.Formatter("[%(levelname)s] %(message)s")
    console_handler.setFormatter(console_formatter)

    # Attach handlers
    logger.addHandler(file_handler)
    logger.addHandler(console_handler)

    return logger
