#  (c) Copyright Leonardo S.p.A. and Leonardo MW Ltd. All rights reserved.
#      Any right of industrial and intellectual property on this document,
#      and of technical Know-how herein contained, belongs to
#      Leonardo S.p.a. and Leonardo MW Ltd.and/or third parties.
#      According to the law, it is forbidden to disclose, reproduce or however
#      use this document and any data herein contained for any use without
#      previous written authorization by Leonardo S.p.a. and Leonardo MW Ltd.

import logging
from pathlib import Path
from logging import config
from datetime import datetime


BASE_DIR = Path(__file__).parent.parent.resolve()
LOG_DIR = BASE_DIR.joinpath('LOG')


# Logger configuration dictionary
LOGGING_CONFIG = {
    'version': 1,
    'loggers': {
        '': {  # root logger
            'level': 'DEBUG',
            'propagate': False,
            'handlers': ['console_handler', 'file_handler'],
        },
    },
    'handlers': {
        'console_handler': {
            'level': 'INFO',
            'formatter': 'dbg',
            'class': 'logging.StreamHandler',
            'stream': 'ext://sys.stdout',
        },
        'file_handler': {
            'level': 'DEBUG',
            'formatter': 'dbg',
            'class': 'logging.handlers.RotatingFileHandler',
            'encoding': 'UTF-8',
            'filename': LOG_DIR.joinpath('tool.log'),  # fallback log filename: it will be changed later on
            'mode': 'a',
            'maxBytes': 1048576,  # default log size is 1 MiB
            'backupCount': 5  # rotate logs after 5 files
        },
    },
    'formatters': {
        'dbg': {
            'format': '%(asctime)s  %(levelname)-8s   %(message)s'
        },
    },
}


def logger_setup(filename=None, use_timestamp=True):
    print(f"LOG_DIR: {LOG_DIR}")

    if not LOG_DIR.exists():
        print(f'WARNING: log directory \n    {LOG_DIR}\ndoes not exist. Creating it!')
        LOG_DIR.mkdir()

    # validate input, in case of any error warn the user and use fallback values
    if not isinstance(filename, str):
        print('WARNING - logger config: invalid log filename. Using default.')
        filename = 'application.log'

    # Add timestamp to filename if requested
    if use_timestamp:
        timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
        name_parts = filename.rsplit('.', 1)
        if len(name_parts) == 2:
            filename = f"{name_parts[0]}_{timestamp}.{name_parts[1]}"
        else:
            filename = f"{filename}_{timestamp}"

    LOGGING_CONFIG['handlers']['file_handler']['filename'] = LOG_DIR.joinpath(filename).resolve()

    print(f"Log file: {LOGGING_CONFIG['handlers']['file_handler']['filename']}")
    logging.config.dictConfig(LOGGING_CONFIG)
