#!/usr/bin/env python3
"""Request a fresh export connector work, wait, download and check STIX."""
import os,json,time
from pycti import OpenCTIApiClient
api=OpenCTIApiClient(os.environ['OPENCTI_URL'],os.environ['OPENCTI_TOKEN'],log_level='ERROR')
reports=api.report.list(search='SecTools Lab — 釣魚事件建模練習',first=10)
report=next(r for r in reports if r.get('name')=='SecTools Lab — 釣魚事件建模練習')
connector=next(c for c in api.connector.list() if c['name']=='SecTools Lab Export STIX')
prior={w['id'] for w in api.work.get_connector_works(connector['id'])}
query='mutation Export($id:ID!,$input:ExportAskInput!){stixDomainObjectEdit(id:$id){exportAsk(input:$input){id name}}}'
result=api.query(query,{'id':report['id'],'input':{'format':'application/json','exportType':'full','fileMarkings':[],'contentMaxMarkings':[]}})
files=result['data']['stixDomainObjectEdit']['exportAsk']
assert files, 'No export file requested'
file_id=files[0]['id']
print('PASS export request: new connector work requested',flush=True)
deadline=time.monotonic()+180
while time.monotonic()<deadline:
    works=[w for w in api.work.get_connector_works(connector['id']) if w['id'] not in prior]
    errors=[w for w in works if w.get('errors')]
    if errors: raise SystemExit('FAIL export work reported errors; inspect connector-export logs')
    completed=next((w for w in works if w['status']=='complete'),None)
    if completed:
        listing=api.query('query($id:String!){report(id:$id){exportFiles(first:20){edges{node{id name uploadStatus}}}}}',{'id':report['id']})
        actual=next((e['node'] for e in listing['data']['report']['exportFiles']['edges'] if e['node']['name']==completed['name'] and e['node']['uploadStatus']=='complete'),None)
        if not actual:
            time.sleep(2); continue
        raw=api.fetch_opencti_file_by_id(actual['id'])
        assert raw, 'Completed export file could not be downloaded'
        bundle=json.loads(raw)
        assert bundle['type']=='bundle'
        assert any(o.get('type')=='report' for o in bundle['objects'])
        assert any(o.get('type')=='relationship' and o.get('relationship_type')=='uses' for o in bundle['objects'])
        print('PASS export connector: fresh work completed without errors',flush=True)
        print('PASS S3 file download: STIX report and uses relationship verified',flush=True)
        print('RESULT '+json.dumps({'objects':len(bundle['objects']),'bytes':len(raw.encode())}),flush=True)
        break
    time.sleep(3)
else: raise SystemExit('FAIL export did not complete within 180s')
