"""Shared helper for the SecTools MISP lab scripts (Python standard library only).

Reads credentials from lab/.env and talks to http://localhost:<MISP_HTTP_PORT>.
Never prints secrets. Intended for this isolated, fictional-data lab only.
"""
import json
import urllib.error
import urllib.request
from pathlib import Path

ROOT = Path(__file__).resolve().parent


def env():
    values = {}
    for line in (ROOT / '.env').read_text().splitlines():
        if '=' in line and not line.lstrip().startswith('#'):
            k, v = line.split('=', 1)
            values[k.strip()] = v.strip()
    return values


ENV = env()
BASE = 'http://localhost:' + ENV.get('MISP_HTTP_PORT', '18081')


class MispError(RuntimeError):
    pass


def api(method, path, body=None, key=None, raw=False, timeout=120):
    """Call the MISP REST API with an auth key; raise on HTTP errors."""
    data = None if body is None else json.dumps(body).encode()
    req = urllib.request.Request(BASE + path, data=data, method=method)
    req.add_header('Authorization', key or ENV['ADMIN_KEY'])
    req.add_header('Accept', 'application/json')
    req.add_header('Content-Type', 'application/json')
    try:
        with urllib.request.urlopen(req, timeout=timeout) as r:
            payload = r.read()
    except urllib.error.HTTPError as e:
        detail = e.read()[:300].decode(errors='replace')
        raise MispError(f'{method} {path} -> HTTP {e.code}: {detail}') from None
    if raw:
        return payload
    return json.loads(payload) if payload else None


def find_event(uuid, key=None):
    """Return the event dict for a UUID, or None when it does not exist / is not visible."""
    hits = api('POST', '/events/restSearch', {'uuid': uuid, 'returnFormat': 'json', 'metadata': False}, key=key)
    events = hits.get('response', []) if isinstance(hits, dict) else hits
    return events[0]['Event'] if events else None
