import json
import os
from datetime import datetime
from hivebee import load_config

def _log_paths():
    config = load_config()
    base = os.path.dirname(os.path.dirname(__file__))
    alerts = os.path.join(base, config.get('logging', {}).get('alerts_log', 'logs/alerts.json'))
    debug  = os.path.join(base, config.get('logging', {}).get('debug_log',  'logs/debug.log'))
    os.makedirs(os.path.dirname(alerts), exist_ok=True)
    os.makedirs(os.path.dirname(debug),  exist_ok=True)
    return alerts, debug

def log_alert(event):
    """
    Append a scored event as a JSON line to alerts.json
    Args: event (dict) — scored event dict
    """
    alerts_log, _ = _log_paths()
    with open(alerts_log, 'a') as f:
        f.write(json.dumps(event) + '\n')

def log_debug(message):
    """
    Write an operational message to debug.log
    Args: message (str)
    """
    _, debug_log = _log_paths()
    ts = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    with open(debug_log, 'a') as f:
        f.write(f"[{ts}] {message}\n")

def read_alerts():
    """
    Read all alerts from alerts.json
    Returns: list of event dicts
    """
    alerts_log, _ = _log_paths()
    if not os.path.exists(alerts_log):
        return []
    alerts = []
    with open(alerts_log) as f:
        for line in f:
            line = line.strip()
            if line:
                try:
                    alerts.append(json.loads(line))
                except json.JSONDecodeError:
                    pass
    return alerts

if __name__ == "__main__":
    test_event = {
        'file': '/home/kali/db_credentials.txt',
        'user': 'root',
        'process': 'cat',
        'timestamp': '2024-01-01 03:00:00',
        'pid': '1234',
        'score': 10,
        'risk_level': 'CRITICAL',
        'reasons': ['root access (+4)', 'credential filename (+2)']
    }
    log_alert(test_event)
    log_debug("Test message from logger")
    alerts = read_alerts()
    print(f"[logger] {len(alerts)} alert(s) in log")
    print(f"[logger] Last alert: {alerts[-1]['risk_level']} — score {alerts[-1]['score']}")
