#!/usr/bin/env python3
"""Import the bundled MISP JSON and STIX 2.1 samples with fresh UUIDs every run, then
read them back, so an old event can never be mistaken for a new import.
Run in lab/: python3 import-check.py. Adds two small fictional events; never deletes."""
import json
import uuid
from pathlib import Path
from misplab import api, find_event

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

# 1. MISP 原生 JSON：模擬收到另一個 MISP 匯出的事件檔
event = json.loads((root / 'sample-event.json').read_text())
event['Event']['uuid'] = str(uuid.uuid4())
api('POST', '/events/add', event)
back = find_event(event['Event']['uuid'])
assert back and {a['value'] for a in back['Attribute']} == {'import-check.example', '198.51.100.23'}
assert 'tlp:clear' in {t['name'] for t in back.get('Tag', [])}
print(f"PASS MISP JSON import: new event {back['uuid'][:8]}… with 2 attributes + tlp:clear")

# 2. STIX 2.1：交由 misp-stix 轉換成 MISP 事件
raw = (root / 'sample-bundle.json').read_text()
run = str(uuid.uuid4())
for kind in ('bundle', 'report', 'indicator'):
    raw = raw.replace(f'{kind}--REPLACED-PER-RUN', f'{kind}--{uuid.uuid4() if kind != "report" else run}')
bundle = json.loads(raw)
result = api('POST', '/events/upload_stix/2', bundle)
imported = find_event(run)
assert imported, 'STIX report did not become a MISP event with the same UUID: ' + json.dumps(result)[:200]
values = {a['value'] for a in imported.get('Attribute', [])} | {a['value'] for o in imported.get('Object', []) for a in o['Attribute']}
assert any('stix-import.example' in v for v in values), values
print(f"PASS STIX 2.1 import: report {run[:8]}… became event {imported['id']}; indicator stix-import.example present")
print('RESULT ' + json.dumps({'misp_json_event': back['uuid'], 'stix_event': run}, ensure_ascii=False))
