import subprocess
import json
import os
import re
from datetime import datetime

def load_baseline():
    """Load honeyfile paths from baseline.json. Returns: list of paths"""
    baseline_path = os.path.join(
        os.path.dirname(os.path.dirname(__file__)), 'logs', 'baseline.json'
    )
    if not os.path.exists(baseline_path):
        return []
    with open(baseline_path) as f:
        return json.load(f).get('honeyfiles', [])

def run_ausearch():
    """Run ausearch for hivebee-tagged events. Returns: str"""
    try:
        result = subprocess.run(
            ['ausearch', '-k', 'hivebee'],
            capture_output=True, text=True
        )
        return result.stdout
    except FileNotFoundError:
        print("[parser] ausearch not found")
        return ""

def parse_ausearch_output(raw):
    """Parse raw ausearch output into event dicts. Returns: list"""
    events = []
    current = {}

    for line in raw.splitlines():
        line = line.strip()

        if line.startswith('----'):
            if current.get('file'):
                events.append(current)
            current = {}
            continue

        m = re.search(r'msg=audit\((\d+\.\d+)', line)
        if m and 'timestamp' not in current:
            try:
                ts = datetime.fromtimestamp(float(m.group(1).split(':')[0]))
                current['timestamp'] = ts.strftime('%Y-%m-%d %H:%M:%S')
            except Exception:
                pass

        m = re.search(r'\bpid=(\d+)', line)
        if m and 'pid' not in current:
            current['pid'] = m.group(1)

        m = re.search(r'\beuid=(\d+)', line)
        if m:
            current['user'] = 'root' if m.group(1) == '0' else m.group(1)

        if 'user' not in current:
            m = re.search(r'\buid=(\d+)', line)
            if m:
                current['user'] = 'root' if m.group(1) == '0' else m.group(1)

        m = re.search(r'\bcomm="([^"]+)"', line)
        if m and 'process' not in current:
            current['process'] = m.group(1)

        if 'process' not in current:
            m = re.search(r'\bexe="([^"]+)"', line)
            if m:
                current['process'] = m.group(1).split('/')[-1]

        m = re.search(r'\bname="([^"]+)"', line)
        if m and 'file' not in current:
            current['file'] = m.group(1)

    if current.get('file'):
        events.append(current)

    return events

def filter_honeyfile_events(events, baseline):
    """Filter to only events matching honeyfile paths. Returns: list"""
    filtered = []
    for event in events:
        for path in baseline:
            if event.get('file') and (
                event['file'] == path or
                event['file'] in path or
                path in event['file']
            ):
                filtered.append(event)
                break
    return filtered

def parse_events():
    """
    Main entry point — returns filtered honeyfile events.
    Returns: list of event dicts
    """
    baseline = load_baseline()
    raw = run_ausearch()
    if not raw:
        return []
    all_events = parse_ausearch_output(raw)
    return filter_honeyfile_events(all_events, baseline)

if __name__ == "__main__":
    events = parse_events()
    if events:
        print(f"[parser] Found {len(events)} event(s):")
        for e in events:
            print(json.dumps(e, indent=2))
    else:
        print("[parser] No honeyfile events found")
