"""Local Drive processing-contract model, not an authenticated Drive client."""
import hashlib
import json
import platform
from pathlib import Path
HERE = Path(__file__).resolve().parent
BASE = {'source_file_id': 'SYN-F01', 'source_version': '7', 'source_drive_id': 'SYN-SHARED-01',
        'source_sha256': hashlib.sha256(b'SYNTHETIC PDF BYTE PLACEHOLDER').hexdigest(),
        'mime_type': 'application/pdf', 'operation': 'review-copy-v1',
        'destination_drive_id': 'SYN-SHARED-01', 'destination_folder_id': 'SYN-FOLDER-09'}

def run(request, current, outputs):
    if not current['access_allowed']:
        return {'state': 'HELD_ACCESS'}
    if request['mime_type'] != 'application/pdf':
        return {'state': 'HELD_EXPORT_REQUIRED'}
    if request['destination_drive_id'] != 'SYN-SHARED-01':
        return {'state': 'REJECTED_DESTINATION_DRIVE'}
    if request['source_version'] != current['version']:
        return {'state': 'HELD_VERSION_CHANGED', 'same_bytes': request['source_sha256'] == current['sha256']}
    key = hashlib.sha256(json.dumps(request, sort_keys=True).encode()).hexdigest()
    if key in outputs:
        return {'state': 'REUSED_OUTPUT', 'job_key': key, 'output': outputs[key]}
    outputs[key] = {'file_id': 'SYN-DERIVATIVE-01', 'source_file_id': request['source_file_id'],
                    'source_version': request['source_version'], 'destination_drive_id': request['destination_drive_id'],
                    'document_bytes': 'NOT_CREATED'}
    return {'state': 'CREATED_MODEL_DERIVATIVE', 'job_key': key, 'output': outputs[key]}

def main():
    state = {'version': '7', 'sha256': BASE['source_sha256'], 'access_allowed': True}
    outputs = {}; cases = []
    for name, request, current, expected in [
        ('normal', BASE, state, 'CREATED_MODEL_DERIVATIVE'),
        ('duplicate_delivery', BASE, state, 'REUSED_OUTPUT'),
        ('metadata_version_changed_same_bytes', BASE, {**state, 'version': '8'}, 'HELD_VERSION_CHANGED'),
        ('wrong_destination_drive', {**BASE, 'destination_drive_id': 'SYN-MY-DRIVE'}, state, 'REJECTED_DESTINATION_DRIVE'),
        ('access_revoked', BASE, {**state, 'access_allowed': False}, 'HELD_ACCESS'),
        ('workspace_document_requires_export', {**BASE, 'mime_type': 'application/vnd.google-apps.document'}, state, 'HELD_EXPORT_REQUIRED')]:
        result = run(request, current, outputs)
        assert result['state'] == expected
        cases.append({'case': name, 'request': request, 'current': current, 'expected': expected, 'result': result})
    assert len(outputs) == 1
    report = {'kind': 'LOCAL_SYNTHETIC_CONTRACT_SIMULATION', 'python': platform.python_version(),
              'network_calls': 0, 'drive_api_test': 'NOT_RUN', 'file_permission_test': 'NOT_RUN',
              'cases_passed': len(cases), 'model_outputs': len(outputs), 'cases': cases,
              'limitations': ['No real Drive revisions, OAuth scopes, downloads or uploads exercised. Model content is a labelled byte placeholder.']}
    (HERE/'processing-contract.json').write_text(json.dumps({'kind': 'PROPOSED_INTERNAL_CONTRACT_NOT_DRIVE_PAYLOAD', **BASE}, indent=2)+'\n')
    (HERE/'simulation-results.json').write_text(json.dumps(report, indent=2)+'\n')
    print(json.dumps({'cases_passed': len(cases), 'python': platform.python_version()}))

if __name__ == '__main__': main()
