"""Local review-record binding, not authentication or a distribution service."""
from __future__ import annotations
import hashlib
import json
from calculator import calculate,check_candidate


def digest(value):
    return hashlib.sha256(json.dumps(value,sort_keys=True,separators=(',',':'),
                                     ensure_ascii=False,allow_nan=False).encode()).hexdigest()


def make_packet(answer):
    evidence=calculate()
    return {'answer':answer,'evidence_sha256':digest(evidence),
            'source_sha256':evidence['source_sha256'],'contract_sha256':evidence['contract_sha256']}


def check_review(packet,decision):
    evidence=calculate();issues=[]
    expected={'answer','evidence_sha256','source_sha256','contract_sha256'}
    if not isinstance(packet,dict) or set(packet)!=expected:
        return {'record_checks_passed':False,'issues':['packet_schema_mismatch'],'distribution':'not_sent'}
    result=check_candidate(packet['answer'],evidence)
    if not result['structured_checks_passed']:issues.append('answer_structural_failure')
    for key,wanted in [('evidence_sha256',digest(evidence)),('source_sha256',evidence['source_sha256']),
                       ('contract_sha256',evidence['contract_sha256'])]:
        if packet[key]!=wanted:issues.append(key+'_mismatch')
    fields={'packet_sha256','reviewer','decision','semantic_review_passed'}
    if not isinstance(decision,dict) or set(decision)!=fields:issues.append('decision_schema_mismatch')
    else:
        if decision['packet_sha256']!=digest(packet):issues.append('reviewed_version_mismatch')
        if not isinstance(decision['reviewer'],str) or not decision['reviewer'].strip():issues.append('missing_reviewer')
        if decision['decision']!='approve':issues.append('not_approved')
        if decision['semantic_review_passed'] is not True:issues.append('semantic_review_not_recorded')
    return {'record_checks_passed':not issues,'issues':issues,'distribution':'not_sent',
            'limits':'Validates local record consistency only. Reviewer identity and truthfulness are not authenticated. No external action is available.'}
