# -*- coding: utf-8 -*-
# Copyright 2025 NXP

# SPDX-License-Identifier: BSD-3-Clause
import inspect
import sys

class InitSequenceLogger:
    def __init__(self):
        self.logs = []

    def log(self, func_name, **kwargs):
        args_str = ", ".join("{}={!r}".format(key, value) for key, value in kwargs.items())
        stack = inspect.stack()
        if len(stack) > 3:
            # In general, the call stack for the init sequence looks like this:
            # [3] The actual calling function
            # [2] errors.py → wrapper() (due to how our code is structured)
            # [1] The init sequence function
            # [0] The current log() function
            caller_frame = stack[3]
            caller_name, caller_file, caller_line = self.extract_frame_info(caller_frame)
        else:
            caller_name = "unknown"
            caller_file = "unknown"
            caller_line = -1
        log_entry = (
            "{0} : {1} \n (called by {2} in {3}:{4})".format(func_name, args_str, caller_name, caller_file, caller_line)
        )
        self.logs.append(log_entry)

    def extract_frame_info(self, frame):
        if sys.version_info[0] < 3:
            # Python 2.x: frame is a tuple with the following structure
            # 0	frame
            # 1	filename
            # 2	lineno
            # 3	function
            # 4	code_context
            # 5	index
            function_name = frame[3]
            filename = frame[1]
            lineno = frame[2]
        else:
            # Python 3.x: frame is a FrameInfo object
            function_name = frame.function
            filename = frame.filename
            lineno = frame.lineno

        return function_name, filename, lineno

    def write_logs_to_file(self, filename):
        with open(filename, 'w') as f:
            for index, log_entry in enumerate(self.logs):
                hex_index = "0x%02X" % index  # Format index as 0xXX
                f.write("command %s %s\n" % (hex_index, log_entry))

    def get_logs(self):
        return self.logs

    def clear_logs(self):
        self.logs = []

islogger = InitSequenceLogger()
