#!/usr/bin/env python3
"""Upload the supplied fictional STIX bundle and wait for the import connector.
Run: docker compose cp sample-bundle.json worker:/tmp/sectools-sample.json
     docker compose exec -T worker python < connector-check.py
"""
import os, json, time, uuid
from pathlib import Path
from pycti import OpenCTIApiClient
from stix2 import parse
api=OpenCTIApiClient(os.environ['OPENCTI_URL'],os.environ['OPENCTI_TOKEN'],log_level='ERROR')
raw=Path('/tmp/sectools-sample.json').read_text()
bundle=json.loads(raw)
parse(raw)  # Fail locally if it is not valid STIX.
report_object=next(o for o in bundle['objects'] if o['type']=='report')
run_id=uuid.uuid4().hex[:12]
report_object['id']='report--'+str(uuid.uuid4())
report_object['name'] += ' / '+run_id
raw=json.dumps(bundle,ensure_ascii=False)
connector=next(c for c in api.connector.list() if c['name']=='SecTools Lab Import STIX')
prior={w['id'] for w in api.work.get_connector_works(connector['id'])}
print('PASS fixture: valid STIX 2.1; fictional reserved .example domain',flush=True)
result=api.upload_file(file_name='sectools-connector-'+run_id+'.json',data=raw.encode(),mime_type='application/json')
file_id=result['data']['uploadImport']['id']
print('PASS uploaded STIX file to platform import area',flush=True)
# Auto-enabled INTERNAL_IMPORT_FILE connector handles application/json.
deadline=time.monotonic()+180
while time.monotonic()<deadline:
    matches=api.report.list(search=report_object['name'],first=10)
    found=next((r for r in matches if r.get('name')==report_object['name']),None)
    works=[w for w in api.work.get_connector_works(connector['id']) if w['id'] not in prior]
    complete=next((w for w in works if w['status']=='complete' and not w.get('errors')),None)
    if found and complete:
        print('PASS connector -> queue -> worker: imported report can be queried',flush=True)
        domain=next(o for o in bundle['objects'] if o['type']=='domain-name')
        observables=api.stix_cyber_observable.list(search=domain['value'],first=10)
        observable=next((o for o in observables if o.get('observable_value')==domain['value']),None)
        assert observable and observable['observable_value']==domain['value']
        print('PASS new work complete without errors; old report cannot satisfy this run',flush=True)
        print('PASS imported observable: connector-check.example',flush=True)
        print('RESULT '+json.dumps({'report_id':found['id'],'uploaded_file':file_id},ensure_ascii=False),flush=True)
        break
    time.sleep(3)
else:
    raise SystemExit('FAIL import not visible within 180s; inspect connector-import and worker logs')
