"""Run inside misp-core, which ships PyMISP: docker compose exec -T misp-core python3 < pymisp-check.py
Reads the admin key from the container environment, talks to nginx on the Compose network,
never prints credentials. Read-only except for one sighting on the training IP."""
import os
import uuid
from pymisp import PyMISP, MISPSighting, __version__

misp = PyMISP('http://misp-nginx:8080', os.environ['ADMIN_KEY'], ssl=False, timeout=60)
print(f"PASS PyMISP {__version__} connected: MISP {misp.misp_instance_version['version']}")

CASE = str(uuid.uuid5(uuid.UUID('6f1c9a52-7d0b-4f36-9a51-5ec7001ab000'), 'sectools-lab-phishing-case'))
event = misp.get_event(CASE, pythonify=True)
print(f'PASS get_event by UUID: {event.info} ({len(event.attributes)} attributes, {len(event.objects)} object)')

ids = misp.search(controller='attributes', type_attribute='ip-dst', to_ids=True, published=True,
                  tags=['tlp:clear'], pythonify=True)
assert '192.0.2.10' in {a.value for a in ids}
print(f'PASS search attributes(ip-dst, to_ids, published, tlp:clear): {len(ids)} hit(s)')

# 不指定排序時，同一查詢的不同頁可能重疊；分頁一定要搭配穩定排序。
pages = [misp.search(controller='events', eventinfo='SecTools Lab%', limit=2, page=p, metadata=True,
                     order='Event.id ASC', pythonify=True) for p in (1, 2, 3, 4)]
seen = [e.uuid for page in pages for e in page]
assert len(seen) == len(set(seen)) and not pages[-1]
print(f'PASS stable pagination (order=Event.id ASC): pages = {[len(p) for p in pages]}, no overlap')

attr = next(a for a in event.attributes if a.value == '192.0.2.10')
s = MISPSighting()
s.from_dict(value='192.0.2.10', source='SecTools Lab SIEM (fictional)', type='0')
misp.add_sighting(s, attr)
sightings = misp.sightings(attr)
print(f'PASS sighting recorded on 192.0.2.10: total sightings = {len(sightings)}')
