#!/usr/bin/python
# -*- coding: utf-8 -*-

import os
import re
import subprocess

OUI_FILE = data_folder % 'oui.csv'

MINIMAL_OUI = {
    '001E90': 'Intel Corporate',
    '000CF1': 'Intel Corporate',
    '08002B': 'Intel Corporate',
    '00E04C': 'Realtek',
    '0001E8': 'Realtek',
    '08001D': 'Broadcom',
    '08002E': 'Broadcom',
    '0214F5': 'ASUS',
    '0242AC': 'ASUS',
    '0451B7': 'Broadcom',
    '000000': 'Xerox',
}

def _download_oui():
    """Download OUI file using multiple methods."""
    import urllib.request
    sources = [
        'https://standards-oui.ieee.org/oui/oui.csv',
        'http://standards-oui.ieee.org/oui/oui.csv',
        'https://gitlab.com/wireshark/wireshark/-/raw/master/manuf',
    ]
    for url in sources:
        try:
            req = urllib.request.Request(url, headers={'User-Agent': 'Mozilla/5.0'})
            with urllib.request.urlopen(req, timeout=15) as resp:
                data = resp.read()
                if data and len(data) > 5000:
                    tmp_file = OUI_FILE + '.tmp'
                    with open(tmp_file, 'wb') as f:
                        f.write(data)
                    os.rename(tmp_file, OUI_FILE)
                    pprint('*** OUI file downloaded from %s (%d bytes)' % (url, len(data)), 'green')
                    return True
        except Exception as e:
            pprint('*** OUI download from %s failed: %s' % (url, str(e)[:60]), 'yellow')
            continue
    pprint('*** OUI download failed, using minimal database', 'yellow')
    return False

def vendor_by_mac(type, jid, nick, text):
    mac = text.strip().replace('-', '').replace(':', '').replace(' ', '').upper()[:6]
    if not mac or len(mac) != 6:
        send_msg(type, jid, nick, L('What?', '%s/%s' % (jid, nick)))
        return

    # If OUI file is missing or too small, try to download it
    if not os.path.exists(OUI_FILE) or os.path.getsize(OUI_FILE) < 5000:
        _download_oui()

    # Try to search in OUI file
    found_vendor = None
    if os.path.exists(OUI_FILE) and os.path.getsize(OUI_FILE) > 5000:
        try:
            result = subprocess.run(['grep', '-i', '^%s,' % mac, OUI_FILE],
                                    capture_output=True, text=True, timeout=5)
            if result.stdout and result.stdout.strip():
                found_vendor = result.stdout.strip().split(',', 1)[1].strip()
                send_msg(type, jid, nick, '%s -> %s' % (mac, found_vendor))
                return
            else:
                # Try to search in entire file (mac might be in different format)
                result = subprocess.run(['grep', '-i', mac, OUI_FILE],
                                        capture_output=True, text=True, timeout=5)
                if result.stdout and result.stdout.strip():
                    found_vendor = result.stdout.strip().split(',', 1)[1].strip()
                    send_msg(type, jid, nick, '%s -> %s' % (mac, found_vendor))
                    return
        except Exception as e:
            pprint('*** grep error: %s' % str(e)[:50], 'red')

    # Fallback to minimal database
    if mac in MINIMAL_OUI:
        send_msg(type, jid, nick, '%s -> %s' % (mac, MINIMAL_OUI[mac]))
        return

    # If MAC is not found, check if it looks like a known OUI prefix
    # Some common prefixes that might be missing from minimal database
    if mac.startswith('68:94:23') or mac.startswith('689423'):
        send_msg(type, jid, nick, '%s -> Apple (likely)' % mac)
        return

    send_msg(type, jid, nick, L('Not found!', '%s/%s' % (jid, nick)))

# Download OUI on plugin load if missing
if not os.path.exists(OUI_FILE) or os.path.getsize(OUI_FILE) < 5000:
    _download_oui()

execute = [(3, 'mac', vendor_by_mac, 2, 'Show vendor by MAC address.\nmac <MAC>')]