"""Teaching record assessment only; never import or call the reservation code."""
import hashlib
import json
from pathlib import Path

HERE = Path(__file__).resolve().parent


def exact_equal(actual, expected):
    """Avoid bool/int equality and require the full declared object shape."""
    if type(actual) is not type(expected):
        return False
    if type(expected) is dict:
        return actual.keys() == expected.keys() and all(
            exact_equal(actual[key], value) for key, value in expected.items())
    if type(expected) is list:
        return len(actual) == len(expected) and all(
            exact_equal(a, e) for a, e in zip(actual, expected))
    return actual == expected


def load_inputs():
    bindings = json.loads((HERE / 'bindings.json').read_text())
    for name, wanted in bindings['sha256'].items():
        if hashlib.sha256((HERE / name).read_bytes()).hexdigest() != wanted:
            raise ValueError('Input identity mismatch: ' + name)
    question = json.loads((HERE / 'question.json').read_text())
    selected = json.loads((HERE / 'selection.json').read_text())
    result = []
    for item in selected:
        raw = json.loads((HERE / item['raw_file']).read_text())
        rows = [row for row in raw['cases'] if row['id'] == item['case_id']]
        if len(rows) != 1:
            raise ValueError('Expected one retained case: ' + item['record_id'])
        result.append((item, raw, rows[0]))
    return question, bindings, result


def decision(record_id, eligibility, observation, reason):
    return {'record_id': record_id, 'eligibility': eligibility,
            'observation': observation, 'reason': reason,
            'intent_authority': 'author_draft_not_approved',
            'reliance_decision': 'not_assessed'}


def assess_weak(item, raw, case, question, bindings):
    """Deliberately bad: trust the embedded comparison, skip scope and calls."""
    value = case['business_oracle_comparison']
    outcome = 'pass' if value is True else 'fail' if value is False else 'not_assessed'
    return decision(item['record_id'], 'eligible', outcome, 'selected_record')


def assess_corrected(item, raw, case, question, bindings):
    """Assess this selected question; adverse evidence can remain eligible."""
    record_id = item['record_id']
    if not exact_equal(case['retry_at_hours'], question['elapsed_hours']) or \
            case['oracle_status'] != 'draft_requirement':
        return decision(record_id, 'ineligible', 'not_assessed', 'outside_selected_question')

    config_name = 'retained/guide05/snapshots/' + item['snapshot'] + '.json'
    wanted_config = json.loads((HERE / config_name).read_text())
    bound = (raw['snapshot'] == item['snapshot'] and
             exact_equal(raw['configuration'], wanted_config) and
             raw['inputs_sha256']['reservation.py'] == bindings['sha256']['retained/guide05/reservation.py'] and
             raw['inputs_sha256']['harness.py'] == bindings['sha256']['retained/guide05/harness.py'] and
             raw['inputs_sha256']['requirement.json'] == bindings['sha256']['retained/guide05/requirement.json'] and
             raw['inputs_sha256']['cases.json'] == bindings['sha256']['retained/guide05/cases.json'] and
             raw['inputs_sha256']['snapshots/' + item['snapshot'] + '.json'] == bindings['sha256'][config_name] and
             case['callable_fingerprint']['source_sha256'] == bindings['sha256']['retained/guide05/reservation.py'] and
             case['callable_fingerprint']['function'] == 'ReservationStore.reserve')
    if not bound:
        return decision(record_id, 'invalid', 'not_assessed', 'binding_mismatch')

    calls = [{'phase': 'setup', 'key': 'client-key-1', 'now_hours': 0},
             {'phase': 'retry', 'key': 'client-key-1', 'now_hours': 12}]
    returns = [{'phase': 'setup', 'returned': case['first_id'], 'returned_type': 'int'},
               {'phase': 'retry', 'returned': case['retry_id'], 'returned_type': 'int'}]
    if not exact_equal(case['observed_real_calls'], calls) or \
            not exact_equal(case['observed_real_returns'], returns):
        return decision(record_id, 'invalid', 'not_assessed', 'missing_retry_invocation')
    if not exact_equal(case['first_id'], 1) or \
            not exact_equal(case['before_reservation_rows'], [[1]]):
        return decision(record_id, 'invalid', 'not_assessed', 'setup_mismatch')

    # Literal expectations independently authored from the retained draft.
    # Neither captured verdicts nor configured retention supply the oracle.
    passes = (exact_equal(case['retry_id'], 1) and
              case['retry_id_type'] == 'int' and
              exact_equal(case['actual_reservation_rows'], [[1]]))
    return decision(record_id, 'eligible', 'pass' if passes else 'fail', 'selected_record')
