#!/usr/bin/env python3
"""Create a private dashboard from imported real public CISA / MITRE intelligence.

Run only after the corresponding connector checks pass. This script reads the
source knowledge, creates one uniquely named workspace, and never publishes it.
Dashboard filters and widget queries are reconciled by full pagination and IDs.

docker --context colima-opencti-tutorial compose -f lab/compose.yaml exec -T \
  -e DASHBOARD_CISA_EXPECTED=1808 \
  -e DASHBOARD_MITRE_AUTHOR_ID=<verified-identity-id> \
  -e DASHBOARD_MITRE_EXPECTED=<verified-count> worker python < lab/dashboard-osint.py

Omit both MITRE variables to build a CISA-only dashboard. Counts are assertions
for the verified local import, not constants describing future source releases.
No source data, sharing settings, connector settings or inferred links change.
"""
import base64
import copy
import hashlib
import json
import os
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]


def out(label, value):
    print(label + ' ' + json.dumps(value, ensure_ascii=False), flush=True)


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


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


def rows(selection, first=500, after=None):
    return q('''query($filters:FilterGroup!,$first:Int!,$after:ID){
      stixCoreObjects(filters:$filters,first:$first,after:$after,orderBy:name,orderMode:asc){
        edges{node{id entity_type ... on Vulnerability{name x_opencti_cisa_kev createdBy{id name}}
          ... on AttackPattern{name createdBy{id name}}}}
        pageInfo{endCursor hasNextPage globalCount}}}''',
        {'filters': selection, 'first': first, 'after': after})['stixCoreObjects']


def total(selection):
    return q('''query($filters:FilterGroup!){stixCoreObjectsNumber(filters:$filters){count total}}''',
             {'filters': selection})['stixCoreObjectsNumber']['total']


def reconcile(source):
    selected = source['filters']
    before = total(selected)
    found, cursor, pages = [], None, 0
    while True:
        page = rows(selected, after=cursor)
        assert page['pageInfo']['globalCount'] == before, 'Import changed while paginating; rerun after completion'
        found.extend(edge['node'] for edge in page['edges'])
        pages += 1
        if not page['pageInfo']['hasNextPage']:
            break
        assert page['pageInfo']['endCursor'] and page['pageInfo']['endCursor'] != cursor
        cursor = page['pageInfo']['endCursor']
    ids = [node['id'] for node in found]
    assert len(ids) == len(set(ids)) == before == total(selected) == source['expected']
    assert before > 0 and all(node['entity_type'] == source['kind'] for node in found)
    assert all(node['createdBy'] and node['createdBy']['id'] == source['author'] for node in found)
    if source['kind'] == 'Vulnerability':
        assert all(node['x_opencti_cisa_kev'] is True for node in found)
    preview = [edge['node'] for edge in rows(selected, first=10)['edges']]
    assert [node['id'] for node in preview] == ids[:10], 'List preview disagrees with complete sorted pagination'
    negative = copy.deepcopy(selected)
    negative['filters'].append({'key': ['name'], 'values': ['No matching OSINT dashboard '+RUN], 'operator': 'eq', 'mode': 'or'})
    assert total(negative) == 0 and rows(negative, first=10)['edges'] == []
    out('PASS SOURCE', {'source': source['label'], 'kind': source['kind'], 'author_id': source['author'],
        'number_total': before, 'paginated_unique_ids': len(ids), 'pages': pages,
        'sorted_id_sha256': hashlib.sha256('\n'.join(sorted(ids)).encode()).hexdigest(),
        'list_preview': [{'id': n['id'], 'name': n['name']} for n in preview],
        'negative_control': 'extra impossible name yields List=[] and Number.total=0'})
    return ids


def selection(source):
    empty = {'mode': 'and', 'filters': [], 'filterGroups': []}
    return {'label': source['label'], 'number': 10, 'sort_by': 'name', 'sort_mode': 'asc',
        'attribute': 'entity_type', 'date_attribute': 'created_at', 'perspective': 'entities', 'isTo': True,
        'filters': copy.deepcopy(source['filters']), 'dynamicFrom': copy.deepcopy(empty), 'dynamicTo': copy.deepcopy(empty),
        'columns': [{'attribute': 'name', 'label': 'Name'}, {'attribute': 'createdBy'}, {'attribute': 'objectMarking'}]}


def main():
    out('RUN', {'id': RUN, 'utc': datetime.now(timezone.utc).isoformat()})
    initial = q('query{about{version} me{id}}')
    out('PLATFORM', initial['about'])
    cisa_filter = filters('Vulnerability', 'x_opencti_cisa_kev', 'true')
    cisa_preview = rows(cisa_filter, first=1)['edges']
    assert cisa_preview, 'Import and verify CISA first'
    author = cisa_preview[0]['node']['createdBy']
    assert author and author['name'] == 'Cybersecurity and Infrastructure Security Agency'
    sources = [{'label': 'CISA KEV 已知遭利用弱點', 'kind': 'Vulnerability', 'author': author['id'],
                'expected': int(os.environ['DASHBOARD_CISA_EXPECTED']), 'filters': cisa_filter}]
    mitre_author, mitre_expected = os.getenv('DASHBOARD_MITRE_AUTHOR_ID'), os.getenv('DASHBOARD_MITRE_EXPECTED')
    assert bool(mitre_author) == bool(mitre_expected), 'Supply both verified MITRE variables or neither'
    if mitre_author:
        mf = filters('Attack-Pattern', 'createdBy', mitre_author)
        preview = rows(mf, first=1)['edges']
        assert preview and preview[0]['node']['createdBy']['name'] == 'The MITRE Corporation'
        sources.append({'label': 'MITRE ATT&CK 來源技術資料', 'kind': 'Attack-Pattern',
                        'author': mitre_author, 'expected': int(mitre_expected), 'filters': mf})
    verified = [reconcile(source) for source in sources]
    manifest = {'config': {}, 'widgets': {}}
    for index, source in enumerate(sources):
        for kind in ('number', 'list'):
            identifier = str(uuid.uuid4())
            title = source['label'] + ('｜資料筆數' if kind == 'number' else '｜依名稱排序・前 10 筆')
            manifest['widgets'][identifier] = {'id': identifier, 'type': kind, 'perspective': 'entities',
                'parameters': {'title': title}, 'dataSelection': [selection(source)],
                'layout': {'i': identifier, 'x': index*6, 'y': 0 if kind == 'number' else 2,
                           'w': 6, 'h': 2 if kind == 'number' else 6, 'moved': False, 'static': False}}
    encoded = base64.b64encode(json.dumps(manifest, ensure_ascii=False).encode()).decode()
    name = 'SecTools｜公開情資工作台｜'+RUN
    description = ('CISA KEV 與 MITRE ATT&CK 的獨立來源檢視；兩欄不代表弱點與技術有直接關係。'
                   if len(sources) == 2 else 'CISA KEV 官方公開情資檢視。')
    if len(sources) == 2:
        description += 'MITRE 篩選未另排除 deprecated 項目，總數不等於現行有效技術數。'
    description += '數字是平台中符合篩選的資料筆數，不是組織風險分數。依名稱排序，非 CISA dateAdded。由 sectools.tw 維護。'
    created = q('mutation($input:WorkspaceAddInput!){workspaceAdd(input:$input){id}}',
        {'input': {'name': name, 'type': 'dashboard',
          'description': description}})['workspaceAdd']
    q('mutation($id:ID!,$input:[EditInput!]!){workspaceFieldPatch(id:$id,input:$input){id}}',
      {'id': created['id'], 'input': [{'key': 'manifest', 'value': [encoded]}]})
    read = q('query($id:String!){workspace(id:$id){id name type manifest authorizedMembers{member_id access_right}}}',
             {'id': created['id']})['workspace']
    actual = json.loads(base64.b64decode(read['manifest']))
    assert actual == manifest and read['type'] == 'dashboard'
    assert read['authorizedMembers'] == [{'member_id': initial['me']['id'], 'access_right': 'admin'}]
    for source, expected_ids in zip(sources, verified):
        # Repeat complete reconciliation from the saved widget filters, not an independent approximation.
        widgets = [w for w in actual['widgets'].values() if w['dataSelection'][0]['filters'] == source['filters']]
        assert {w['type'] for w in widgets} == {'number', 'list'} and len(widgets) == 2
        saved_source = dict(source, filters=widgets[0]['dataSelection'][0]['filters'])
        assert reconcile(saved_source) == expected_ids, 'Data changed between verification and saved dashboard readback'
    out('PASS DASHBOARD', {'id': read['id'], 'name': name, 'widgets': len(manifest['widgets']),
        'explicit_members': 'creator only (admin)', 'public_dashboard_created': False})
    print('LIMIT API-created configuration and real widget query reconciliation; UI rendering is a separate check. '
          'Platform administrators may have access beyond explicit members. No public URI, inferred source relationship, '
          'organization-specific risk or CISA dateAdded chart was created. Counts reflect this import and can change.', flush=True)
    print('RESULT PASS private real-intelligence dashboard', flush=True)


if __name__ == '__main__':
    main()
