# Copyright (C) 2022 Thomas Hoppe (h0bB1T). All rights reserved.
#
# Unauthorized copying of this file via any medium is strictly prohibited.
# Proprietary and confidential.

import bpy

import sys, traceback

from typing import Optional
from time import time

log_prefix = 'SNW'

def debug_level():
    return 3

def err(m: str):
    print(f'[{log_prefix}-ERR] {m}')
    print(traceback.format_exc())

def wrn(m: str): 
    if debug_level() > 0: 
        print(f'[{log_prefix}-WRN] {m}')

def inf(m: str): 
    if debug_level() > 1: 
        print(f'[{log_prefix}-INF] {m}')

def dbg(m: str): 
    if debug_level() > 2: 
        print(f'[{log_prefix}-DBG] {m}')

def dmp(m: str): 
    if debug_level() > 3: 
        print(f'[{log_prefix}-DMP] {m}')


def log_exception(exc: Exception, *, operator: Optional[bpy.types.Operator] = None, context_msg: str = ""):
    """
    Log an exception in a consistent way.

    Parameters
    ----------
    exc : Exception
        The caught exception instance.
    operator : bpy.types.Operator or None
        If provided, uses operator.report({'ERROR'}, ...) so the user sees a popup.
        If None, logs to stdout only.
    context_msg : str
        Optional additional context ("while exporting asset", etc).
    """
    msg = f"{log_prefix} {context_msg} Error: {exc}" if context_msg else f"{log_prefix} Error: {exc}"

    # Always print traceback for debugging
    traceback.print_exc(file=sys.stderr)

    if operator is not None:
        try:
            operator.report({'ERROR'}, msg)
        except Exception:
            # Fallback: report() might not exist if called in wrong context
            print(f"{log_prefix} Could not report to operator UI: {msg}")
    else:
        print(msg)            

        