#!/usr/bin/env python3
"""Owned citation/delivery fixture; not a semantic or content-safety classifier.

Offsets are Python Unicode code-point offsets with an exclusive end. Sources and
permissions and the keyword-only principal are fixture authority, not real IAM.
A principal claimed inside the proposal is ignored.
"""
from dataclasses import dataclass
import hashlib
import json


@dataclass(frozen=True)
class Source:
    text: str
    label: str

    @property
    def digest(self):
        return hashlib.sha256(self.text.encode('utf-8')).hexdigest()


SOURCES = {
    'public-note': Source('The rehearsal starts at 09:00.\nThis note grants no permission to act.', 'public'),
    'internal-note': Source('SYNTHETIC INTERNAL REVIEW NOTE.', 'restricted'),
    'unicode-note': Source('caf\u00e9 opens at 09:00.', 'public'),
}
PERMISSIONS = {('researcher', 'internal-note', 'private-review')}


def check(proposal, *, principal='reader', sources=SOURCES, permissions=PERMISSIONS):
    result = {'citation_integrity': 'not_checked', 'claim_support': 'NOT_EVALUATED',
              'output_content_safety': 'NOT_EVALUATED', 'source_delivery_scope': 'hold'}
    if not isinstance(proposal, dict):
        result['citation_integrity'] = 'invalid_request'
        return result
    if (not isinstance(proposal.get('source'), str) or
            not isinstance(proposal.get('destination'), str) or not isinstance(principal, str)):
        result['citation_integrity'] = 'invalid_request'
        return result
    source = sources.get(proposal.get('source'))
    if source is None:
        result['citation_integrity'] = 'unknown_source'
        return result
    if proposal.get('source_sha256') != source.digest:
        result['citation_integrity'] = 'revision_mismatch'
        return result
    start, end = proposal.get('start'), proposal.get('end')
    if (type(start) is not int or type(end) is not int or not 0 <= start < end <= len(source.text)):
        result['citation_integrity'] = 'invalid_span'
        return result
    if proposal.get('quote') != source.text[start:end]:
        result['citation_integrity'] = 'excerpt_mismatch'
        return result
    result['citation_integrity'] = 'matched_exact_source_span'
    if source.label == 'public' and proposal.get('destination') == 'public-report':
        result['source_delivery_scope'] = 'allowed_by_fixture_source_policy'
    elif source.label == 'restricted' and (
            principal, proposal.get('source'), proposal.get('destination')) in permissions:
        result['source_delivery_scope'] = 'allowed_by_fixture_source_policy'
    # An allowed source scope does not authorize an action or approve output content.
    return result


def proposal(source_id='public-note', **changes):
    source = SOURCES[source_id]
    end = source.text.index('.') + 1
    request = {'source': source_id, 'source_sha256': source.digest, 'start': 0, 'end': end,
               'quote': source.text[:end], 'principal': 'reader', 'destination': 'public-report',
               'claim': 'The rehearsal starts at 09:00.'}
    request.update(changes)
    return request


def replay():
    cases = {
        'public_exact_excerpt': proposal(),
        'same_excerpt_false_claim': proposal(claim='The rehearsal starts at 18:00.'),
        'forged_excerpt': proposal(quote='The rehearsal starts at 18:00.'),
        'changed_source_revision': proposal(source_sha256='0' * 64),
        'restricted_exact_excerpt_public_destination': proposal('internal-note', claimed_label='public', claimed_authorized=True),
        'restricted_exact_excerpt_private_authorized_destination': proposal('internal-note', principal='researcher', destination='private-review'),
    }
    return {'kind': 'owned_citation_integrity_and_source_scope_fixture',
            'actual_model_or_private_document_test': False,
            'cases': {name: check(request, principal=('researcher' if name ==
                       'restricted_exact_excerpt_private_authorized_destination' else 'reader'))
                      for name, request in cases.items()},
            'boundary': 'exact source spans do not prove claim support, approve content, or grant action authority'}


if __name__ == '__main__':
    print(json.dumps(replay(), indent=2))
