import smtplib
import subprocess
import os
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from hivebee import load_config

def send_desktop_notification(event):
    """
    Send a desktop notification via notify-send.
    Args: event (dict) — scored event dict
    """
    try:
        title = f"🐝 HiveBee — {event.get('risk_level', 'ALERT')}"
        body = (
            f"File: {event.get('file', 'unknown')}\n"
            f"User: {event.get('user', 'unknown')}\n"
            f"Process: {event.get('process', 'unknown')}\n"
            f"Score: {event.get('score', 0)}/10"
        )
        urgency = 'critical' if event.get('risk_level') == 'CRITICAL' else 'normal'
        subprocess.run(
            ['notify-send', '-u', urgency, '-t', '8000', title, body],
            capture_output=True
        )
        print(f"[alerter] Desktop notification sent")
    except Exception as e:
        print(f"[alerter] Desktop notification failed: {e}")

def send_email(event):
    """
    Send an alert email via SMTP.
    Args: event (dict) — scored event dict
    """
    config = load_config()
    email_cfg = config.get('alerts', {}).get('email', {})

    if not email_cfg.get('enabled', False):
        return

    smtp_host = email_cfg.get('smtp_host', '')
    smtp_port = email_cfg.get('smtp_port', 587)
    from_addr = email_cfg.get('from', '')
    to_addr   = email_cfg.get('to', '')
    password  = email_cfg.get('password', '')

    if not all([smtp_host, from_addr, to_addr]):
        print("[alerter] Email not configured — check config/default_config.yaml")
        return

    subject = f"[HiveBee] {event.get('risk_level')} Alert — {event.get('file', '').split('/')[-1]}"

    body = f"""
HiveBee Intrusion Detection — Alert Fired
==========================================

Risk Level : {event.get('risk_level')}
Score      : {event.get('score')}/10
File       : {event.get('file')}
User       : {event.get('user')}
Process    : {event.get('process')}
Timestamp  : {event.get('timestamp')}
Reasons    : {', '.join(event.get('reasons', []))}

-- HiveBee IDS
"""

    try:
        msg = MIMEMultipart()
        msg['From']    = from_addr
        msg['To']      = to_addr
        msg['Subject'] = subject
        msg.attach(MIMEText(body, 'plain'))

        with smtplib.SMTP(smtp_host, smtp_port) as server:
            server.ehlo()
            server.starttls()
            if password:
                server.login(from_addr, password)
            server.sendmail(from_addr, to_addr, msg.as_string())

        print(f"[alerter] Email sent to {to_addr}")
    except Exception as e:
        print(f"[alerter] Email failed: {e}")

def alert(event):
    """
    Main alert dispatcher — sends all configured alerts.
    Args: event (dict) — scored event dict
    Returns: None
    """
    config = load_config()
    notify_on = config.get('alerts', {}).get('notify_on', 'CRITICAL')

    risk_order = {'LOW': 1, 'MEDIUM': 2, 'HIGH': 3, 'CRITICAL': 4}
    event_level  = risk_order.get(event.get('risk_level', 'LOW'), 1)
    trigger_level = risk_order.get(notify_on, 4)

    if event_level < trigger_level:
        return

    send_desktop_notification(event)
    send_email(event)

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)']
    }
    alert(test_event)
