#!/usr/bin/env python3
"""Verify distribution levels with a second, fictional organisation on the same instance.
Creates (or reuses) org 'SecTools Partner Lab', a User-role account, a sharing group and two
events; issues a temporary auth key for the partner, checks what it can see, then deletes
only that temporary key. Run in lab/: python3 sharing-check.py after verify.py."""
import uuid
from misplab import api, find_event

NS = uuid.UUID('6f1c9a52-7d0b-4f36-9a51-5ec7001ab000')
CASE = str(uuid.uuid5(NS, 'sectools-lab-phishing-case'))          # verify.py, distribution 0
COMMUNITY = str(uuid.uuid5(NS, 'sectools-lab-community-advisory'))  # distribution 1
GROUP_ONLY = str(uuid.uuid5(NS, 'sectools-lab-sharing-group-note'))  # distribution 4
PARTNER, EMAIL, SG = 'SecTools Partner Lab', 'analyst@partner-lab.test', 'SecTools Lab Trust Circle'

assert find_event(CASE), 'run verify.py first'
orgs = {o['Organisation']['name']: o['Organisation'] for o in api('GET', '/organisations/index/scope:all')}
partner = orgs.get(PARTNER) or api('POST', '/admin/organisations/add', {'name': PARTNER, 'local': True,
                                   'description': 'Fictional partner for the sharing exercise.'})['Organisation']
own = next(o for o in orgs.values() if o['name'] == 'SecTools Lab')
users = {u['User']['email']: u['User'] for u in api('GET', '/admin/users/index')}
user = users.get(EMAIL) or api('POST', '/admin/users/add', {'email': EMAIL, 'org_id': partner['id'], 'role_id': 3})['User']
print(f"PASS partner org + User-role account ready: {PARTNER} (local), role_id={user['role_id']}")

groups = {g['SharingGroup']['name']: g for g in api('GET', '/sharing_groups/index')['response']}
if SG not in groups:
    sg = api('POST', '/sharing_groups/add', {'name': SG, 'releasability': 'Fictional training circle only.',
                                             'active': True})['SharingGroup']
    api('POST', f"/sharing_groups/addOrg/{sg['id']}/{partner['id']}")
else:
    sg = groups[SG]['SharingGroup']
print(f'PASS sharing group ready: {SG} (SecTools Lab + partner)')


def ensure(event_uuid, info, distribution, sg_id=None):
    if not find_event(event_uuid):
        body = {'uuid': event_uuid, 'info': info, 'date': '2026-11-27', 'distribution': distribution,
                'threat_level_id': 3, 'analysis': 2,
                'Attribute': [{'type': 'comment', 'category': 'Other', 'value': info, 'to_ids': False}]}
        if sg_id:
            body['sharing_group_id'] = sg_id
        event = api('POST', '/events/add', {'Event': body})['Event']
        api('POST', f"/events/publish/{event['id']}")


ensure(COMMUNITY, 'SecTools Lab — 社群公告（虛構，distribution=1）', 1)
ensure(GROUP_ONLY, 'SecTools Lab — 信任圈備註（虛構，distribution=4）', 4, sg['id'])

key = api('POST', f"/auth_keys/add/{user['id']}", {'comment': 'temporary sharing-check key'})['AuthKey']
try:
    seen = {
        'your organisation only (0)': find_event(CASE, key=key['authkey_raw']) is not None,
        'this community only (1)': find_event(COMMUNITY, key=key['authkey_raw']) is not None,
        'sharing group (4)': find_event(GROUP_ONLY, key=key['authkey_raw']) is not None,
    }
    community_id = find_event(COMMUNITY)['id']
    try:
        api('POST', f'/events/edit/{community_id}', {'Event': {'info': 'tampered by partner'}}, key=key['authkey_raw'])
        can_edit = True
    except Exception:
        can_edit = False
finally:
    api('POST', f"/auth_keys/delete/{key['id']}")
assert seen == {'your organisation only (0)': False, 'this community only (1)': True, 'sharing group (4)': True}, seen
for level, visible in seen.items():
    print(f"PASS partner visibility — {level}: {'visible' if visible else 'hidden'}")
assert can_edit is False and 'tampered' not in find_event(COMMUNITY)['info']
print('PASS partner can read the community event but cannot edit it; temporary key deleted')
