import streamlit as st
from utils.library.param import get_Param
from utils.library.util import get_value_from_cache

 

def get_logger(logname):
    import logging
    import sys
    import traceback
    import warnings
    import builtins
    from io import StringIO

    cc = get_value_from_cache()
    if f'log_writer_{logname}' not in cc:

        cc[f'log_buffer_{logname}'] =  StringIO()
        st.session_state.log_buffer = cc[f'log_buffer_{logname}']

        # 2. Configurar logger
        logger = logging.getLogger(logname)
        cc[f'log_writer_{logname}'] = logger
        logger.setLevel(logging.INFO)

        # Limpa handlers duplicados se rodar múltiplas vezes
        if not logger.handlers:
            memory_handler = logging.StreamHandler(cc[f'log_buffer_{logname}'])
            memory_handler.setFormatter(logging.Formatter("%(asctime)s [%(levelname)s] %(message)s"))
            logger.addHandler(memory_handler)

            # Também exibe no terminal
            console_handler = logging.StreamHandler(sys.stdout)
            console_handler.setFormatter(logging.Formatter("%(asctime)s [%(levelname)s] %(message)s"))
            logger.addHandler(console_handler)

    
        # 4. Capturar exceptions
        def log_uncaught_exceptions(exctype, value, tb):
            logger.error("".join(traceback.format_exception(exctype, value, tb)))
        sys.excepthook = log_uncaught_exceptions

        # 5. Capturar warnings
        def log_warning(message, category, filename, lineno, file=None, line=None):
            logger.warning(f"{filename}:{lineno}: {category.__name__}: {message}")
        warnings.showwarning = log_warning
    else:
        logger = cc[f'log_writer_{logname}'] 
    return logger 

def reset_logger(logger_name):
    import builtins, sys, warnings
    logger = get_logger(logger_name)

    if logger:

        # 1. Limpa handlers
        for handler in logger.handlers[:]:
            logger.removeHandler(handler)
            handler.close()

        # 3. Restaura exceções
        sys.excepthook = sys.__excepthook__

        # 4. Restaura warnings
        warnings.showwarning = warnings._showwarnmsg_impl
    
        cc = get_value_from_cache()
        if f'log_writer_{logger_name}' in cc:
            del cc[f'log_writer_{logger_name}'] 
        if f'log_buffer_{logger_name}' in cc:
            del cc[f'log_buffer_{logger_name}']

@st.cache_resource()  
def get_locale():
    return get_Param('sys_license_locale',"")

@st.cache_resource()
def get_css():
    if get_Param('sys_apply_stylecss','false') == 'true':
        with open('static/css/style.css','r') as _css:
            return _css.read()
    else:
        return ''
@st.cache_resource()
def get_aggrid_css():
    with open('static/css/ag-theme-xdash.css','r') as _css:
        return _css.read()

@st.cache_resource   
def get_api_started():
    return {'api_started':0}

@st.cache_resource()
def init_welcome():
    return get_Param('sys_init_welcome',None)

@st.cache_resource()
def init_login():
    return get_Param('sys_init_login',None)

@st.cache_resource
def get_scheduler_started():
    return {'scheduler_started':0}

  
 