#!/usr/bin/env python3
"""API-only CE verification: notifications, batch task, sanity dry-run, decay.

Run from repository root via the existing worker (no tokens printed):
docker --context colima-opencti-tutorial compose -f lab/compose.yaml \
  exec -T worker python < lab/analysis-check.py
Creates only uniquely named fictional lab objects; keeps evidence objects.
Own triggers are disconnected and own decay rules disabled in finally.
Never requests a data-sanity repair or sends email/webhooks.
"""
import json
import os
import time
import uuid
from datetime import datetime, timezone
from pycti import OpenCTIApiClient

api = OpenCTIApiClient(os.environ['OPENCTI_URL'], os.environ['OPENCTI_TOKEN'], log_level='ERROR')
RUN = uuid.uuid4().hex[:12]
cleanup = []


def log(text):
    print(text, flush=True)


def query(document, variables=None):
    result = api.query(document, variables)
    assert result.get('data') and not result.get('errors'), 'GraphQL request failed'
    return result['data']


def wait_for(check, description, timeout=150):
    end = time.monotonic() + timeout
    while time.monotonic() < end:
        result = check()
        if result:
            return result
        time.sleep(2)
    raise RuntimeError('Timed out: ' + description)


def filters(key, values):
    return {'mode': 'and', 'filters': [{'key': [key], 'values': values,
            'operator': 'eq', 'mode': 'or'}], 'filterGroups': []}


def indicators():
    label = api.label.create(value='sectools-decay-' + RUN, color='#00acc1')
    exclusion_label = api.label.create(value='sectools-no-decay-' + RUN, color='#00acc1')
    scoped = filters('objectLabel', [label['id']])
    scoped['filters'].append({'key':['x_opencti_main_observable_type'],
                             'values':['Domain-Name'],'operator':'eq','mode':'or'})
    rule = query('''mutation($input:DecayRuleAddInput!){decayRuleAdd(input:$input){id name active}}''',
        {'input':{'name':'SecTools Lab 30 day ' + RUN,'active':True,'order':100,
         'decay_filters':json.dumps(scoped),'decay_lifetime':30,'decay_pound':1,
         'decay_points':[60,40],'decay_revoke_score':20}})['decayRuleAdd']
    cleanup.append(('decayRuleFieldPatch',rule['id']))
    excluded = filters('objectLabel',[exclusion_label['id']])
    exrule = query('''mutation($input:DecayExclusionRuleAddInput!){decayExclusionRuleAdd(input:$input){id}}''',
        {'input':{'name':'SecTools Lab no decay ' + RUN,'active':True,
         'decay_exclusion_filters':json.dumps(excluded)}})['decayExclusionRuleAdd']
    cleanup.append(('decayExclusionRuleFieldPatch',exrule['id']))
    fields = '''id name x_opencti_score valid_from valid_until revoked
       decay_applied_rule{decay_rule_id decay_lifetime decay_revoke_score}
       decay_exclusion_applied_rule{decay_exclusion_id decay_exclusion_name}'''
    objects = []
    for kind, labels in [('scoped',[label['id']]),('excluded',[label['id'],exclusion_label['id']]),('control',[])]:
        obj = query('mutation($input:IndicatorAddInput!){indicatorAdd(input:$input){'+fields+'}}',
          {'input':{'name':'SecTools Lab ' + kind + ' indicator ' + RUN,
           'pattern':"[domain-name:value = '" + kind + '-' + RUN + ".example']",
           'pattern_type':'stix','x_opencti_main_observable_type':'Domain-Name',
           'x_opencti_score':80,'objectLabel':labels,'createObservables':False,
           'description':'Fictional technical exercise; no malicious classification.'}})['indicatorAdd']
        objects.append(obj)
    assert objects[0]['decay_applied_rule']['decay_rule_id'] == rule['id']
    assert objects[0]['decay_applied_rule']['decay_lifetime'] == 30
    assert objects[1]['decay_exclusion_applied_rule']['decay_exclusion_id'] == exrule['id']
    assert objects[2]['decay_applied_rule']['decay_rule_id'] != rule['id']
    assert not objects[2]['decay_exclusion_applied_rule']
    log('PASS indicator initial rule selection: scoped 30-day rule; exclusion takes priority; unlabelled control unaffected')
    log('ARTIFACT indicator snapshots ' + json.dumps(objects,ensure_ascii=False))
    log('LIMIT no accelerated clock, elapsed 30-day decay or eventual revocation tested; existing excluded indicators retain exclusion after disabling the rule')


def main():
    log('RUN ' + RUN + ' UTC ' + datetime.now(timezone.utc).isoformat())
    state = query('query { about {version} me{id} notificationNotifiers{id name} }')
    log('PASS API connected: OpenCTI ' + state['about']['version'])
    ui = next(n for n in state['notificationNotifiers'] if n['name'] == 'User interface')
    report = api.report.create(name='SecTools Lab notification ' + RUN,
        description='Fictional notification exercise; not threat intelligence.',
        published=datetime.now(timezone.utc).isoformat(), report_types=['threat-report'])
    trigger = query('''mutation($input:TriggerLiveAddInput!){
      triggerKnowledgeLiveAdd(input:$input){id name event_types notifiers{id}}}''',
      {'input': {'name': 'SecTools Lab UI notification ' + RUN, 'instance_trigger': True,
       'event_types': ['update'], 'notifiers': [ui['id']], 'recipients': [state['me']['id']],
       'filters': json.dumps(filters('ids', [report['id']]))}})['triggerKnowledgeLiveAdd']
    cleanup.append(('triggerKnowledgeFieldPatch', trigger['id']))
    log('ARTIFACT report ' + report['id'] + '; trigger ' + trigger['id'])
    # Let the periodic notification manager observe this isolated trigger.
    time.sleep(5)
    query('''mutation($id:ID!,$input:[EditInput]!){reportEdit(id:$id){fieldPatch(input:$input){id}}}''',
          {'id':report['id'],'input':[{'key':'description',
           'value':['Fictional notification exercise; verified update ' + RUN]}]})

    def notification():
        data = query('''query {notifications(first:100,orderBy:created,orderMode:desc){
          edges{node{id name user_id created_at notification_content{title events{
            entity_internal_id instance_id operation message}}}}}}''')['notifications']['edges']
        for edge in data:
            node = edge['node']
            if (node['user_id'] != state['me']['id']
                    or node['name'] != trigger['name']):
                continue
            for content in node['notification_content']:
                for event in content['events']:
                    if (event.get('operation') == 'update'
                            and report['id'] in [event.get('entity_internal_id'), event.get('instance_id')]):
                        return node
        return None
    notice = wait_for(notification, 'in-app notification')
    log('PASS in-app notification received: ' + json.dumps(notice, ensure_ascii=False))

    label = api.label.create(value='sectools-batch-' + RUN, color='#00acc1')
    objects = [api.stix_cyber_observable.create(simple_observable_id=None,
        observableData={'type':'domain-name','value':'batch-' + str(i) + '-' + RUN + '.example'},
        x_opencti_description='Fictional background task exercise') for i in range(3)]
    ids = [o['id'] for o in objects[:2]]
    task = query('''mutation($input:ListTaskAddInput!){listTaskAdd(input:$input){id}}''',
      {'input': {'ids': ids, 'scope': 'KNOWLEDGE', 'description': 'SecTools Lab batch ' + RUN,
       'actions': [{'type':'ADD','context':{'type':'RELATION','field':'object-label','values':[label['id']]}}]}})['listTaskAdd']
    def completed():
        task_state = query('''query($id:String!){backgroundTask(id:$id){id completed
          task_expected_number task_processed_number errors{id message}}}''', {'id':task['id']})['backgroundTask']
        return task_state if task_state['completed'] else None
    result = wait_for(completed, 'background label task')
    assert (not result['errors'] and result['task_processed_number'] == 2
            and result['task_expected_number'] == 2)
    def labels_visible():
        selected_ready = True
        for index, item in enumerate(objects):
            read = query('query($id:String!){stixCyberObservable(id:$id){id objectLabel{id value}}}',
                         {'id':item['id']})['stixCyberObservable']
            applied = label['id'] in [l['id'] for l in read['objectLabel']]
            if index == 2:
                assert not applied, 'Batch modified the unselected control'
            else:
                selected_ready = selected_ready and applied
        return selected_ready
    # The background task can complete before relation indexing is visible.
    wait_for(labels_visible, 'selected labels visible; control remains untouched', timeout=60)
    log('PASS background task completed; labels on exactly 2 selected objects, absent on control: ' + json.dumps(result))
    log('ARTIFACT batch domains ' + json.dumps([o['id'] for o in objects]) + '; label ' + label['id'])

    operations = query('query {dataSanityOperations{identifier is_running}}')['dataSanityOperations']
    assert any(o['identifier']=='caseSensitiveDuplicatedId' for o in operations)
    dry = query('''query{dataSanityOperationDryRun(operation_name:"caseSensitiveDuplicatedId"){
      estimated_impact{key count}}}''')['dataSanityOperationDryRun']
    log('PASS Data sanity read-only dry run (no repair mutation): ' + json.dumps(dry))
    indicators()


def finish_cleanup():
    failures = []
    for mutation, identifier in reversed(cleanup):
        try:
            if mutation == 'triggerKnowledgeFieldPatch':
                # Trigger has no active flag. An empty notifier list stops delivery.
                result = query('mutation($id:ID!,$input:[EditInput!]!){' + mutation +
                      '(id:$id,input:$input){id notifiers{id}}}',
                      {'id':identifier, 'input':[{'key':'notifiers','value':[]}]})[mutation]
                assert result['notifiers'] == [], 'Trigger delivery still connected'
                log('PASS cleanup: own trigger notifiers cleared ' + identifier)
            else:
                result = query('mutation($id:ID!,$input:[EditInput!]!){' + mutation +
                      '(id:$id,input:$input){id active}}',
                      {'id':identifier, 'input':[{'key':'active','value':[False]}]})[mutation]
                assert not result['active']
                log('PASS cleanup: own decay rule disabled ' + identifier)
        except Exception as error:
            failures.append(identifier)
            # Avoid dumping arbitrary API errors that may contain configuration.
            log('FAIL cleanup: ' + identifier + ' (' + type(error).__name__ + ')')
    if failures:
        raise RuntimeError('Cleanup failed for own artifacts: ' + ', '.join(failures))


if __name__ == '__main__':
    try:
        main()
    finally:
        finish_cleanup()
