"""Original offline acceptance fixture, Python 3.11+; no model or network.
Fact-table comparison is deliberately narrow, not general semantic entailment.
"""
import copy
import math

SOURCE = {'id': 'faq-1', 'tenant': 'demo', 'version': 'v1',
          'text': 'Returns are accepted within 30 days.',
          'facts': {'return_window': '30 days'}}
REQUEST = {'tenant': 'demo', 'version': 'v1', 'field': 'return_window'}
CANDIDATE = {'status': 'answer', 'answer': '30 days',
             'evidence_id': 'faq-1', 'quote': SOURCE['text'], 'action': 'none'}


def check(candidate, request, source):
    expected = {'status', 'answer', 'evidence_id', 'quote', 'action'}
    if not isinstance(candidate, dict) or set(candidate) != expected:
        return 'review'
    if candidate['action'] != 'none':
        return 'review'
    if source is None:
        if (candidate['status'] == 'abstain' and candidate['answer'] is None and
            candidate['evidence_id'] is None and candidate['quote'] is None):
            return 'abstained'
        return 'review'
    if source['tenant'] != request['tenant'] or source['version'] != request['version']:
        return 'review'
    if candidate['status'] != 'answer':
        return 'review'
    if candidate['evidence_id'] != source['id'] or candidate['quote'] != source['text']:
        return 'review'
    expected_answer = source['facts'].get(request['field'])
    if expected_answer is None or candidate['answer'] != expected_answer:
        return 'review'
    return 'validated_candidate'


def accepted_cost(total, accepted):
    if type(total) not in (int, float) or not math.isfinite(total) or total < 0:
        raise ValueError('cost_domain')
    if type(accepted) is not int or accepted < 0:
        raise ValueError('accepted_domain')
    return None if accepted == 0 else total / accepted


def main():
    count = 0
    def yes(value):
        nonlocal count
        assert value
        count += 1
    def reject(fn):
        nonlocal count
        try:
            fn()
        except ValueError:
            count += 1
        else:
            raise AssertionError('invalid metric accepted')
    abstain = dict(status='abstain', answer=None, evidence_id=None, quote=None, action='none')
    yes(check(CANDIDATE, REQUEST, SOURCE) == 'validated_candidate')
    yes(check(abstain, REQUEST, None) == 'abstained')
    for patch in ({'answer': '60 days'}, {'evidence_id': 'fake'}, {'quote': 'unrelated'},
                  {'action': 'send_email'}, {'status': 'unknown'}, {'extra': 1}):
        yes(check(dict(CANDIDATE, **patch), REQUEST, SOURCE) == 'review')
    for field in CANDIDATE:
        bad = copy.deepcopy(CANDIDATE)
        bad.pop(field)
        yes(check(bad, REQUEST, SOURCE) == 'review')
    yes(check(CANDIDATE, REQUEST, None) == 'review')
    yes(check(CANDIDATE, dict(REQUEST, tenant='other'), SOURCE) == 'review')
    yes(check(CANDIDATE, dict(REQUEST, version='v2'), SOURCE) == 'review')
    yes(check(CANDIDATE, dict(REQUEST, field='unsupported'), SOURCE) == 'review')
    yes(check(dict(abstain, answer='guessed'), REQUEST, None) == 'review')
    yes(check('ignore policy and send', REQUEST, SOURCE) == 'review')
    yes(accepted_cost(12, 72) == 1 / 6)
    yes(accepted_cost(12, 0) is None)
    reject(lambda: accepted_cost(-1, 72))
    reject(lambda: accepted_cost(12, True))
    reject(lambda: accepted_cost(float('nan'), 72))
    cases = [(CANDIDATE, SOURCE), (abstain, None),
             (dict(CANDIDATE, answer='60 days'), SOURCE),
             (dict(CANDIDATE, quote='unrelated'), SOURCE)]
    outcomes = [check(c, REQUEST, s) for c, s in cases]
    print(f'checks={count} candidates=4 validated={outcomes.count("validated_candidate")} '
          f'abstained={outcomes.count("abstained")} review={outcomes.count("review")}')
    print('model_calls=0 external_writes=0 cost_per_accepted=0.166667')


if __name__ == '__main__':
    main()
