#!/usr/bin/env python3
"""Isolated CE ruleApply, exclusion-list and enrichment-discovery checks.

Run inside the existing worker; no rule activation, global scan, external API,
synchronizer or Connector deployment. Retains unique fictional data. Disables
only the exclusion list created by this run, even after failure.
"""
import json
import os
import sys
import time
import uuid
from datetime import datetime, timezone
from pycti import OpenCTIApiClient
from pycti.api.opencti_api_client import File

TOKEN = os.environ['OPENCTI_TOKEN']
api = OpenCTIApiClient(os.environ['OPENCTI_URL'], TOKEN, log_level='ERROR')
RUN = uuid.uuid4().hex[:12]
RULE_ID = 'part-of_targets'
EXCLUSION_ID = None
BASELINE = None
FAILURES = []
ARTIFACTS = {'run': RUN}


def log(message):
    print(str(message).replace(TOKEN, '[REDACTED]'), flush=True)


def q(document, variables=None):
    result = api.query(document, variables)
    if result.get('errors') or not result.get('data'):
        raise RuntimeError('GraphQL errors or missing data')
    return result['data']


def wait_for(label, check, timeout=150):
    deadline = time.monotonic() + timeout
    notice = time.monotonic() + 30
    while time.monotonic() < deadline:
        value = check()
        if value:
            return value
        if time.monotonic() >= notice:
            log('WAIT ' + label)
            notice += 30
        time.sleep(2)
    raise RuntimeError('Timed out: ' + label)


def case(label, action):
    log('CASE ' + label)
    try:
        action()
    except Exception as error:
        message = type(error).__name__ + ': ' + str(error).replace(TOKEN, '[REDACTED]')
        FAILURES.append({'case': label, 'error': message})
        log('FAIL ' + label + ' ' + message)


def rules():
    return q('query{rules{id name activated} ruleManagerInfo{id activated}}')


REL_FIELDS = '''id standard_id relationship_type is_inferred
  from{... on IntrusionSet{id name} ... on Organization{id name}}
  to{... on IntrusionSet{id name} ... on Organization{id name}}
  x_opencti_inferences{rule{id name} explanation{
    ... on StixCoreRelationship{id relationship_type is_inferred}
  }}'''


def edges(source, target):
    result = q('query($from:[String],$to:[String]){stixCoreRelationships(fromId:$from,toId:$to,first:10){edges{node{' + REL_FIELDS + '}}}}',
               {'from': [source], 'to': [target]})
    return [e['node'] for e in result['stixCoreRelationships']['edges']]


def infer():
    selected = next(r for r in BASELINE['rules'] if r['id'] == RULE_ID)
    assert selected['name'] == 'Targeting propagation via belonging'
    assert not any(rule['activated'] for rule in BASELINE['rules']), 'This isolated lab expects all rules inactive'
    actor = api.intrusion_set.create(name='SecTools Lab Inference Actor ' + RUN,
        description='Fictional isolated rule exercise; no real threat attribution.')
    child = api.identity.create(type='Organization', name='SecTools Lab Inference Child ' + RUN,
        description='Fictional child organization; isolated rule fixture.')
    parent = api.identity.create(type='Organization', name='SecTools Lab Inference Parent ' + RUN,
        description='Fictional parent organization; isolated rule fixture.')
    read_back = q('query($search:String!){intrusionSets(search:$search,first:10){edges{node{id name}}} identities(search:$search,first:10){edges{node{id name}}}}', {'search': RUN})
    ARTIFACTS['objects'] = [edge['node'] for group in read_back.values() for edge in group['edges']]
    assert {obj['id'] for obj in ARTIFACTS['objects']} == {actor['id'], child['id'], parent['id']}
    assert not edges(actor['id'], parent['id'])
    direct = []
    for source, target, kind in [(actor, child, 'targets'), (child, parent, 'part-of')]:
        item = q('mutation($input:StixCoreRelationshipAddInput!){stixCoreRelationshipAdd(input:$input){' + REL_FIELDS + '}}',
          {'input': {'fromId': source['id'], 'toId': target['id'], 'relationship_type': kind,
                     'description': 'Explicit fictional training assumption / ' + RUN, 'confidence': 50}})['stixCoreRelationshipAdd']
        assert item['is_inferred'] is False and not item['x_opencti_inferences']
        direct.append(item)
    ARTIFACTS['direct_edges'] = direct
    assert not edges(actor['id'], parent['id']), 'Derived edge existed before scoped ruleApply'
    log('PASS direct assumptions: targets + part-of are non-inferred; no actor-to-parent edge yet')
    # Runtime source: executeRuleApply loads only this ID, builds one creation
    # event, and passes only this rule to rulesApplyHandler. No activation call.
    response = q('mutation($element:ID!,$rule:ID!){ruleApply(elementId:$element,ruleId:$rule)}',
                 {'element': direct[0]['id'], 'rule': RULE_ID})
    ARTIFACTS['rule_apply_response'] = response
    derived = wait_for('scoped targets inference', lambda: next(
        (r for r in edges(actor['id'], parent['id']) if r['relationship_type'] == 'targets' and r['is_inferred']), None))
    evidence = [x for x in derived['x_opencti_inferences'] if x['rule']['id'] == RULE_ID]
    assert evidence, 'No matching inference rule evidence'
    source_ids = {r['id'] for r in direct}
    assert any(source_ids <= {e['id'] for e in item['explanation']} for item in evidence), 'Explanation does not include both source edges'
    assert derived['id'] not in source_ids
    assert all(any(r['id'] == source['id'] and r['is_inferred'] is False for r in edges(source['from']['id'], source['to']['id'])) for source in direct)
    after = rules()
    assert {r['id']: r['activated'] for r in after['rules']} == {r['id']: r['activated'] for r in BASELINE['rules']}
    ARTIFACTS['derived_edge'] = derived
    log('PASS scoped ruleApply created inferred targets; explanation references both exact direct edge IDs')
    log('PASS all rule activation states unchanged; no global rule scan requested')
    log('EVIDENCE ' + json.dumps({'objects': ARTIFACTS['objects'], 'direct_edges': direct, 'derived_edge': derived}, ensure_ascii=False))


def synchronized():
    status = q('query{exclusionListCacheStatus{refreshVersion cacheVersion isCacheRebuildInProgress}}')['exclusionListCacheStatus']
    return status if not status['isCacheRebuildInProgress'] and status['refreshVersion'] == status['cacheVersion'] else None


def add_indicator(value):
    return q('mutation($input:IndicatorAddInput!){indicatorAdd(input:$input){id name pattern}}',
      {'input': {'name': 'SecTools Lab exclusion ' + value, 'pattern': "[domain-name:value = '" + value + "']",
                 'pattern_type': 'stix', 'x_opencti_main_observable_type': 'Domain-Name',
                 'createObservables': False, 'x_opencti_score': 10,
                 'description': 'Fictional exclusion-list test; not a malicious classification.'}})['indicatorAdd']


def exclusions():
    global EXCLUSION_ID
    blocked = 'blocked-' + RUN + '.example'
    allowed = 'allowed-' + RUN + '.example'
    created = q('mutation($input:ExclusionListFileAddInput!){exclusionListFileAdd(input:$input){id name enabled exclusion_list_values_count exclusion_list_entity_types}}',
      {'input': {'name': 'SecTools Lab exact exclusion ' + RUN, 'description': 'One exact fictional domain only / ' + RUN,
                 'exclusion_list_entity_types': ['Domain-Name'],
                 'file': File('sectools-exclusion-' + RUN + '.txt', blocked, 'text/plain')}})['exclusionListFileAdd']
    EXCLUSION_ID = created['id']
    ARTIFACTS['exclusion_list'] = created
    assert created['enabled'] is True and created['exclusion_list_values_count'] == 1, created
    assert created['exclusion_list_entity_types'] == ['Domain-Name']
    ARTIFACTS['exclusion_list'] = created
    ARTIFACTS['exclusion_cache'] = wait_for('new exclusion list synchronized', synchronized)
    try:
        add_indicator(blocked)
    except ValueError as error:
        message = str(error)
        assert 'Indicator of type stix is contained in exclusion list' in message, 'Unexpected error, not exclusion rejection'
        log('PASS exact blocked STIX Indicator rejected by exclusion list: ' + blocked)
    else:
        raise AssertionError('Blocked Indicator was unexpectedly created')
    control = add_indicator(allowed)
    assert control and control['pattern'] == "[domain-name:value = '" + allowed + "']"
    observable = api.stix_cyber_observable.create(simple_observable_id=None,
        observableData={'type': 'domain-name', 'value': blocked},
        x_opencti_description='Fictional value remains valid as an Observable, not an Indicator.')
    actual = q('query($id:String!){stixCyberObservable(id:$id){id observable_value}}', {'id': observable['id']})['stixCyberObservable']
    assert actual and actual['observable_value'] == blocked
    matches = q('query($search:String!){indicators(search:$search,first:10){edges{node{id pattern}}}}', {'search': blocked})['indicators']['edges']
    assert not any(blocked in edge['node']['pattern'] for edge in matches)
    ARTIFACTS['allowed_indicator'] = control
    ARTIFACTS['blocked_observable'] = {'id': actual['id'], 'value': actual['observable_value']}
    log('PASS control Indicator created; excluded value still allowed as standalone Observable; no blocked Indicator found')


def enrichment_boundary():
    connectors = q('query{enrichmentConnectors(type:"Domain-Name"){id name active auto connector_type connector_scope}}')['enrichmentConnectors']
    ARTIFACTS['domain_enrichment_connectors'] = connectors
    assert connectors == [], 'Available enrichment changed; do not invoke unknown external providers'
    log('PASS enrichment discovery boundary: Domain-Name has no available enrichment connector; no external query or result claimed')


def main():
    global BASELINE
    log('RUN ' + RUN + ' UTC ' + datetime.now(timezone.utc).isoformat())
    log('SCOPE API checks on unique fictional data; no UI, global activation, Connector deployment, or external source requests')
    ARTIFACTS['version'] = q('query{about{version}}')['about']['version']
    BASELINE = rules()
    ARTIFACTS['rule_baseline'] = BASELINE
    log('BASELINE ' + json.dumps(BASELINE))
    case('isolated CE ruleApply inference', infer)
    case('exact-value exclusion list positive/negative', exclusions)
    case('enrichment availability boundary', enrichment_boundary)


if __name__ == '__main__':
    try:
        main()
    except Exception as error:
        FAILURES.append({'case': 'setup', 'error': str(error).replace(TOKEN, '[REDACTED]')})
        log('FAIL setup ' + str(error))
    finally:
        if EXCLUSION_ID:
            try:
                stopped = q('mutation($id:ID!,$input:[EditInput!]){exclusionListFieldPatch(id:$id,input:$input){id enabled}}',
                            {'id': EXCLUSION_ID, 'input': [{'key': 'enabled', 'value': ['false']}]})['exclusionListFieldPatch']
                assert stopped['enabled'] is False
                wait_for('disabled exclusion synchronized', synchronized)
                log('PASS cleanup: own exclusion list disabled and cache synchronized ' + EXCLUSION_ID)
            except Exception as error:
                FAILURES.append({'case': 'cleanup', 'error': str(error).replace(TOKEN, '[REDACTED]')})
        log('RESULT ' + json.dumps(ARTIFACTS, ensure_ascii=False))
        log('FAILURES ' + json.dumps(FAILURES, ensure_ascii=False))
        log('LIMIT scoped manual rule application only; no live global rule activation/cleanup, cross-marking inference matrix, enrichment execution, or external threat evidence')
    sys.exit(1 if FAILURES else 0)
