import sys
import typing
from enum import Enum
import os
from datetime import datetime
from .. import Configuration

class Severity(Enum):
    FATAL = 0
    WTF = 1
    ERROR = 2
    WARN = 3
    INFO = 4
    DEBUG = 5
    TRACE = 6

severity_limit_hooks = Severity[Configuration.get_val('logging', 'level').upper()]
severity_limit_file = Severity[Configuration.get_val('logging', 'filelevel').upper()]
log_file = Configuration.get_val('logging', 'logfile')
hooks: list[typing.Callable] = list()

def add_hook(hook: typing.Callable):
    hooks.append(hook)

def remove_hook(hook: typing.Callable):
    hooks.remove(hook)

def get_caller():
    logging_frame_globals = sys._getframe(2).f_globals
    return logging_frame_globals['__name__']

def write_to_log_file(message):
    """Write log message to file with timestamp"""
    timestamp = datetime.now().strftime("%H:%M:%S")
    log_entry = f"[{timestamp}] {message}\n"

    # Create log directory if it doesn't exist
    log_dir = os.path.dirname(log_file)
    if log_dir and not os.path.exists(log_dir):
        os.makedirs(log_dir)

    with open(log_file, "a") as f:
        f.write(log_entry)

    os.chmod(log_file, 0o600)

def log(message, severity=Severity.INFO):
    caller = get_caller()
    log_hooks(caller, message, severity)
    log_logfile(caller, message, severity)

def log_logfile(caller, message, severity):
    if severity.value > severity_limit_file.value:
        return

    log_message = f'[{severity.name}][{caller}] {message}'
    write_to_log_file(log_message)

def log_hooks(caller, message, severity):
    if severity.value > severity_limit_hooks.value:
        return

    for hook in hooks:
        hook(severity, caller, message)
