"""Read-only intake check. Validation is not identity authentication or gold promotion."""
import argparse
from datetime import datetime
import hashlib
import json
from pathlib import Path

HERE = Path(__file__).resolve().parent
SCHEMA = 'kredo.wave17.composed-review.v1'
SCOPE = 'wave17_exact_selected_answers_and_truth_annotations_not_full_gold_or_promotion'


def unique_object(pairs):
    result = {}
    for key, value in pairs:
        if key in result:
            raise ValueError(f'Duplicate JSON key: {key}')
        result[key] = value
    return result


def load(path):
    raw = Path(path).read_bytes()
    if len(raw) > 8 * 1024 * 1024:
        raise ValueError('Receipt exceeds 8 MiB')
    return json.loads(raw, object_pairs_hook=unique_object)


def verify(receipt, bundle, bundle_hash):
    expected_fields = {'schema', 'interface_version', 'bundle_sha256', 'reviewer_claim', 'exported_at', 'complete', 'applied', 'promotion_authorized', 'scope', 'state'}
    if type(receipt) is not dict or set(receipt) != expected_fields:
        raise ValueError('Receipt fields do not match contract')
    bindings = {'schema': SCHEMA, 'interface_version': bundle['interface_version'], 'bundle_sha256': bundle_hash,
                'reviewer_claim': 'Jim', 'scope': SCOPE}
    for name, expected in bindings.items():
        if receipt[name] != expected:
            raise ValueError(f'Invalid {name}')
    for name in ['complete', 'applied', 'promotion_authorized']:
        if type(receipt[name]) is not bool:
            raise ValueError(f'{name} must be boolean')
    if receipt['applied'] or receipt['promotion_authorized']:
        raise ValueError('Review does not authorize application or promotion')
    if not isinstance(receipt['exported_at'], str) or not receipt['exported_at'].endswith('Z'):
        raise ValueError('Export timestamp must be UTC')
    datetime.fromisoformat(receipt['exported_at'].replace('Z', '+00:00'))
    state = receipt['state']
    if type(state) is not dict or set(state) != {'decisions', 'notes', 'attestation', 'events'}:
        raise ValueError('Invalid state fields')
    if type(state['decisions']) is not dict or type(state['notes']) is not dict or type(state['events']) is not list or type(state['attestation']) is not bool:
        raise ValueError('Invalid state types')
    ids = {i['prompt_id'] for i in bundle['items']}
    keys = {i['prompt_id'] + '::' + d for i in bundle['items'] for d in i['lenses']}
    if not set(state['decisions']).issubset(keys) or not set(state['notes']).issubset(ids):
        raise ValueError('Unknown prompt or lens')
    choices = {'fit': {'yes', 'no', 'discuss'}, 'evidence': {'approve', 'revise', 'discuss'}}
    count, notes_needed = 0, set()
    for key, row in state['decisions'].items():
        if type(row) is not dict or not set(row).issubset(choices):
            raise ValueError('Invalid decision structure')
        for kind, value in row.items():
            if not isinstance(value, str) or value not in choices[kind]:
                raise ValueError('Invalid decision value')
            count += 1
            if (kind == 'fit' and value != 'yes') or (kind == 'evidence' and value != 'approve'):
                notes_needed.add(key.split('::')[0])
    for note in state['notes'].values():
        if not isinstance(note, str) or len(note.encode('utf-16-le')) // 2 > 12000:
            raise ValueError('Invalid note')
    # Events are declared UI history, not proof of reviewer identity or final authority.
    for number, event in enumerate(state['events'], 1):
        if type(event) is not dict or set(event) != {'sequence', 'at', 'type', 'key', 'value'}:
            raise ValueError('Invalid event fields')
        if type(event['sequence']) is not int or event['sequence'] != number:
            raise ValueError('Invalid event sequence')
        if not isinstance(event['at'], str) or not event['at'].endswith('Z'):
            raise ValueError('Invalid event time')
        datetime.fromisoformat(event['at'].replace('Z', '+00:00'))
        kind, key, value = event['type'], event['key'], event['value']
        if kind in choices:
            if key not in keys or not isinstance(value, str) or value not in choices[kind]:
                raise ValueError('Invalid decision event')
        elif kind == 'note':
            if key not in ids or not isinstance(value, str) or len(value.encode('utf-16-le')) // 2 > 12000:
                raise ValueError('Invalid note event')
        elif kind == 'attestation':
            if key != 'Jim' or type(value) is not bool:
                raise ValueError('Invalid attestation event')
        else:
            raise ValueError('Unknown event type')
    missing_notes = sorted(pid for pid in notes_needed if not state['notes'].get(pid, '').strip())
    if receipt['complete'] and (count != len(keys) * 2 or missing_notes or not state['attestation']):
        raise ValueError('Completed review lacks choices, required notes, or attestation')
    return {'valid': True, 'complete': receipt['complete'], 'choices': count, 'missing_notes': missing_notes,
            'human_identity_authenticated': False, 'applied': False, 'promotion_authorized': False}


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('receipt')
    args = parser.parse_args()
    # Trust anchor is this delivered package manifest, not a hash supplied by the export.
    manifest = (HERE / 'SHA256SUMS').read_text().splitlines()
    for line in manifest:
        expected, filename = line.split('  ', 1)
        if '/' in filename or filename.startswith('.'):
            raise ValueError('Unsafe package manifest member')
        if hashlib.sha256((HERE / filename).read_bytes()).hexdigest() != expected:
            raise ValueError(f'Review package changed: {filename}')
    raw = (HERE / 'REVIEW_BUNDLE.json').read_bytes()
    bundle_hash = hashlib.sha256(raw).hexdigest()
    result = verify(load(args.receipt), json.loads(raw), bundle_hash)
    result['receipt_sha256'] = hashlib.sha256(Path(args.receipt).read_bytes()).hexdigest()
    print(json.dumps(result, indent=2))


if __name__ == '__main__':
    main()
