#!/usr/bin/env python3
"""PracticeMark reference scorer.

Reads only the published method file (practicemark-method-1.0.json) and works in exact fractions, so it shares no code and no
rounding with the web page. If this file and the page ever disagree on a score, one of them is wrong and neither may be published.

  python3 practicemark.py PMD3-XXXXX-XXXXX-XXXXX-XXXXX   score a result code
  python3 practicemark.py --check cases.json             run a file of test cases
"""
import json, sys, datetime
from fractions import Fraction
from pathlib import Path

HERE = Path(__file__).parent

class Method:
    def __init__(self, path=HERE / 'practicemark-method-1.0.json'):
        self.m = m = json.loads(Path(path).read_text(encoding='utf-8'))
        self.q = {q['number']: q for q in m['questions']}
        self.by_id = {q['id']: q['number'] for q in m['questions']}
        self.pts = {n: Fraction(str(q['points'])) for n, q in self.q.items()}
        self.share = {n: {a['key']: Fraction(str(a['share'])) for a in q['answers']} for n, q in self.q.items()}
        assert sum(self.pts.values()) == 100, 'points must add up to 100'
        assert all(max(s.values()) == 1 for s in self.share.values()), 'every question needs a full-credit answer'

    def _numbered(self, answers):
        return {(self.by_id[k] if k in self.by_id else int(k)): v for k, v in answers.items()}

    def skipped(self, a):
        out = set()
        for r in self.m['skipRules']:
            if a.get(r['ifQuestion']) == r['isAnswered']: out |= set(r['thenSkip'])
        return out

    def score(self, answers):
        a = self._numbered(answers); skip = self.skipped(a)
        earned = {}
        for n in self.q:
            if n in skip: earned[n] = Fraction(0); continue
            if a.get(n) not in self.share[n]: raise ValueError(f'question {n}: no valid answer')
            earned[n] = self.pts[n] * self.share[n][a[n]]
        total = sum(earned.values())
        score = int(total + Fraction(1, 2))            # halves round up; the total is never negative
        level = next(l['name'] for l in self.m['levels'] if score >= l['from'])
        areas = {}
        for ar in self.m['areas']:
            got = sum(earned[n] for n in ar['questions']); of = sum(self.pts[n] for n in ar['questions'])
            areas[ar['name']] = int(got / of * 100 + Fraction(1, 2))
        gaps = [g['question'] for g in self.m['seriousGaps'] if a.get(g['question']) == g['answer'] and g['question'] not in skip]
        return {'score': score, 'level': level, 'points': str(total) if total.denominator > 1 else str(int(total)),
                'pointsDecimal': float(total), 'areas': areas, 'seriousGaps': gaps, 'skipped': sorted(skip)}

    # ---- result codes
    def _check(self, body):
        al = self.m['resultCode']['alphabet']
        t = sum((i + 1) * al.index(ch) for i, ch in enumerate(body)) % self.m['resultCode']['checkModulus']
        return al[t >> 5] + al[t & 31]

    def encode(self, answers, day):
        rc = self.m['resultCode']; a = self._numbered(answers); skip = self.skipped(a); v = 0
        for n in sorted(self.q):
            keys = [x['key'] for x in self.q[n]['answers']]
            v = v * len(keys) + (0 if n in skip else keys.index(a[n]))
        v = v * rc['dayRange'] + day
        body = ''
        for _ in range(rc['bodyLength']): body = rc['alphabet'][v & 31] + body; v >>= 5
        full = body + self._check(body)
        g = rc.get('groupLength', 6)
        return rc['prefix'] + '-' + '-'.join(full[i:i + g] for i in range(0, len(full), g))

    def decode(self, text):
        rc = self.m['resultCode']; fix = lambda s: s.replace('I', '1').replace('L', '1').replace('O', '0')
        t = fix(''.join(ch for ch in text.upper() if ch.isascii() and ch.isalnum())); pre = fix(rc['prefix'])
        if not t.startswith(pre) or len(t) != len(pre) + rc['bodyLength'] + rc['checkLength']: raise ValueError('format')
        full = t[len(pre):]; body = full[:rc['bodyLength']]
        if any(ch not in rc['alphabet'] for ch in full): raise ValueError('format')
        if self._check(body) != full[rc['bodyLength']:]: raise ValueError('check')
        v = 0
        for ch in body: v = v * 32 + rc['alphabet'].index(ch)
        v, day = divmod(v, rc['dayRange']); a = {}
        for n in sorted(self.q, reverse=True):
            keys = [x['key'] for x in self.q[n]['answers']]
            v, d = divmod(v, len(keys)); a[n] = keys[d]
        if v: raise ValueError('range')
        for n in self.skipped(a): del a[n]
        return a, day

    def date_of(self, day):
        return datetime.date.fromisoformat(self.m['resultCode']['dayZero']) + datetime.timedelta(days=day)

def main(argv):
    M = Method()
    if len(argv) == 3 and argv[1] == '--check':
        cases = json.loads(Path(argv[2]).read_text(encoding='utf-8'))['cases']; bad = 0
        for c in cases:
            got = M.score(c['answers']); exp = c['expected']
            ok = (got['score'] == exp['score'] and got['level'] == exp['level'] and abs(got['pointsDecimal'] - exp['points']) < 1e-9
                  and got['areas'] == exp['areas'] and got['seriousGaps'] == exp['seriousGaps'] and M.encode(c['answers'], c['day']) == c['code'])
            a, day = M.decode(c['code'])
            ok = ok and day == c['day'] and M.score(a)['score'] == exp['score']
            if not ok: bad += 1; print('MISMATCH', c['name'], got, exp) if bad < 6 else None
        print(f'{len(cases)} cases checked, {bad} mismatches'); return 1 if bad else 0
    if len(argv) == 2:
        a, day = M.decode(argv[1]); r = M.score(a); d = M.date_of(day)
        # the score line as the page prints it. A result code holds no evidence level, so a result read from one is self-reported.
        print(f"PracticeMark {r['score']} · {r['level']} · Self-reported · {d.strftime('%B')} {d.day}, {d.year}")
        print(f"Method {M.m['version']}{' draft' if M.m['status'] == 'draft' else ''}. Points earned: {r['pointsDecimal']:g} of 100.")
        for name, v in r['areas'].items(): print(f'  {name:<11}{v:>4}')
        if r['seriousGaps']: print('Serious gaps, by question number:', ', '.join(map(str, r['seriousGaps'])))
        return 0
    print(__doc__); return 2

if __name__ == '__main__':
    sys.exit(main(sys.argv))
