"""Local synthetic CRM mapping exercise. No HubSpot requests, files or notes written."""
import hashlib
import json
import platform
from pathlib import Path
HERE = Path(__file__).resolve().parent
BASE = {'account': 'SYN-PORTAL-01', 'object_type': 'deal', 'record_id': 'SYN-D100',
        'source_case': 'SYN-CASE-77', 'document_id': 'SYN-DOC-09', 'document_revision': '1',
        'mapping_revision': '3', 'operation': 'attach-approved-copy-v1'}
MAPPING = {'account': 'SYN-PORTAL-01', 'object_type': 'deal', 'record_id': 'SYN-D100',
           'source_case': 'SYN-CASE-77', 'mapping_revision': '3', 'record_state': 'ACTIVE'}

def attach(request, current, links):
    if current['record_state'] != 'ACTIVE':
        return {'state': 'HELD_RECORD_STATE'}
    for field in ['account', 'object_type', 'record_id', 'source_case']:
        if request[field] != current[field]:
            return {'state': 'REJECTED_IDENTITY', 'mismatched_field': field}
    if request['mapping_revision'] != current['mapping_revision']:
        return {'state': 'HELD_STALE_MAPPING'}
    key = hashlib.sha256(json.dumps(request, sort_keys=True).encode()).hexdigest()
    if key in links:
        return {'state': 'RECONCILED_EXISTING_LINK', 'job_key': key, 'link': links[key]}
    link = {'file_id': 'SYN-FILE-09', 'note_id': 'SYN-NOTE-22', 'record_id': current['record_id'],
            'account': current['account'], 'object_type': current['object_type'], 'source_case': current['source_case'],
            'document_id': request['document_id'], 'document_revision': request['document_revision']}
    links[key] = link
    return {'state': 'CREATED_MODEL_LINK', 'job_key': key, 'link': link}

def main():
    links = {}; cases = []
    specs = [
        ('approved_mapping', BASE, MAPPING, 'CREATED_MODEL_LINK'),
        ('duplicate_request', BASE, MAPPING, 'RECONCILED_EXISTING_LINK'),
        ('same_customer_name_wrong_record', {**BASE, 'record_id': 'SYN-D101'}, MAPPING, 'REJECTED_IDENTITY'),
        ('wrong_account', {**BASE, 'account': 'SYN-PORTAL-02'}, MAPPING, 'REJECTED_IDENTITY'),
        ('stale_mapping_revision', BASE, {**MAPPING, 'mapping_revision': '4'}, 'HELD_STALE_MAPPING'),
        ('merged_record', BASE, {**MAPPING, 'record_state': 'MERGED'}, 'HELD_RECORD_STATE')]
    for name, request, current, expected in specs:
        result = attach(request, current, links)
        assert result['state'] == expected
        cases.append({'case': name, 'request': request, 'current_mapping': current, 'result': result, 'expected': expected})
    assert len(links) == 1
    report = {'kind': 'LOCAL_SYNTHETIC_MAPPING_TEST', 'python': platform.python_version(), 'network_calls': 0,
              'hubspot_authenticated_test': 'NOT_RUN', 'real_file_upload': 'NOT_RUN',
              'cases_passed': len(cases), 'links_created_in_model': len(links), 'cases': cases,
              'limitations': ['Local guard conditions only; no actual CRM permissions, merge redirects, API response or cross-object behaviour tested.']}
    (HERE/'record-mapping.json').write_text(json.dumps({'kind': 'SYNTHETIC_BUSINESS_MAPPING', 'mapping': MAPPING, 'request': BASE}, indent=2)+'\n')
    (HERE/'mapping-test-results.json').write_text(json.dumps(report, indent=2)+'\n')
    print(json.dumps({'cases_passed': len(cases), 'model_links': len(links), 'python': platform.python_version()}))

if __name__ == '__main__': main()
