from datetime import datetime
from hivebee import load_config

CRED_KEYWORDS = [
    'password', 'passwd', 'credential', 'secret', 'token',
    'api_key', 'private', 'id_rsa', '.env', 'config',
    'backup', 'salary', 'aws', 'auth', 'key', '.txt'
]

NOISE_PROCESSES = ['auditctl', 'auditd', 'python3']

def score_event(event):
    """
    Score a parsed event and add risk metadata.
    Args: event (dict) — canonical event dict from parser
    Returns: event dict with score, risk_level, reasons added
    """
    config = load_config()
    scoring = config.get('scoring', {})
    whitelist = config.get('whitelisted_processes', [])
    whitelist = list(set(whitelist + NOISE_PROCESSES))

    score = 0
    reasons = []

    # Skip pure noise
    if event.get('process') in NOISE_PROCESSES:
        event['score'] = 0
        event['risk_level'] = 'LOW'
        event['reasons'] = ['whitelisted process']
        return event

    # Rule 1 — root access
    if event.get('user') in ('root', '0'):
        pts = scoring.get('root_access_points', 4)
        score += pts
        reasons.append(f"root access (+{pts})")

    # Rule 2 — unknown process
    process = event.get('process', '')
    if process and process not in whitelist:
        pts = scoring.get('unknown_process_points', 3)
        score += pts
        reasons.append(f"unlisted process '{process}' (+{pts})")

    # Rule 3 — after hours
    try:
        ts = datetime.strptime(event.get('timestamp', ''), '%Y-%m-%d %H:%M:%S')
        if ts.hour < 8 or ts.hour >= 20:
            score += 2
            reasons.append("after-hours access (+2)")
    except ValueError:
        pass

    # Rule 4 — credential filename
    filename = (event.get('file') or '').lower()
    if any(kw in filename for kw in CRED_KEYWORDS):
        score += 2
        reasons.append("credential filename (+2)")

    score = min(score, 10)

    threshold = scoring.get('critical_threshold', 7)
    if score >= threshold:
        risk_level = 'CRITICAL'
    elif score >= threshold - 2:
        risk_level = 'HIGH'
    elif score >= threshold - 4:
        risk_level = 'MEDIUM'
    else:
        risk_level = 'LOW'

    event['score'] = score
    event['risk_level'] = risk_level
    event['reasons'] = reasons
    return event

if __name__ == "__main__":
    import json
    test = {
        'file': '/home/kali/db_credentials.txt',
        'user': 'root',
        'process': 'cat',
        'timestamp': '2024-01-01 03:00:00',
        'pid': '1234'
    }
    result = score_event(test)
    print(f"Score: {result['score']} — {result['risk_level']}")
    print(f"Reasons: {result['reasons']}")
