import logging, sys, re, time

class logcolor:
    INFO = '\033[94m'
    REFERENCE = '\033[96m'
    ERROR = '\033[91m'
    SUCCESS = '\033[92m'
    WARNING = '\033[93m'

    ENDC = '\033[0m'
    HEADER = '\033[95m'
    BOLD = '\033[1m'
    UNDERLINE = '\033[4m'

class NoColorFormatter(logging.Formatter):
    """
    Log formatter that strips terminal colour
    escape codes from the log message.
    """

    # Regex for ANSI colour codes
    ANSI_RE = re.compile(r'\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])')

    def format(self, record):
        """Return logger message with terminal escapes removed."""
        return "%s %s %s" % (
            time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),
            re.sub(self.ANSI_RE, "", record.levelname),
            re.sub(self.ANSI_RE, "", record.msg)
        )
    
def build_logger(logpath):
    logger = logging.getLogger()
    logger.setLevel(logging.INFO)
    stdformatter = logging.Formatter("%(message)s")
    fileformatter = NoColorFormatter()

    # logging to both std
    stdout_handler = logging.StreamHandler(sys.stdout)
    stdout_handler.setLevel(logging.DEBUG)
    stdout_handler.setFormatter(stdformatter)

    # concurrently, also log to output file
    file_handler = logging.FileHandler(logpath, mode='w', encoding="utf8")
    file_handler.setLevel(logging.DEBUG)
    file_handler.setFormatter(fileformatter)

    logger.addHandler(file_handler)
    logger.addHandler(stdout_handler)

    return logger


def human_readable_time(seconds):
    parts = []

    hours = int(seconds // 3600)
    if hours:
        parts.append(f"{hours}h")

    minutes = int((seconds % 3600) // 60)
    if minutes:
        parts.append(f"{minutes}m")

    secs = seconds % 60
    if secs or not parts:  # Show seconds if non-zero or if it's the only value
        # Round to 2 decimal places only if there's a fractional component
        if secs.is_integer():
            parts.append(f"{int(secs)}s")
        else:
            parts.append(f"{secs:.2f}s")

    return ", ".join(parts)
