"""Week 16: configuration search; no weight training or model-quality claim."""
import argparse
import hashlib
import json
import tempfile
from pathlib import Path


def candidates():
    return [{'version': f'v{i}', 'threshold': threshold,
             'hypothesis': 'Reject low-confidence proposals without discarding clear cases'}
            for i, threshold in enumerate([0.2, 0.4, 0.5, 0.7, 0.9], 1)]


def score(candidate, cases):
    return [int((confidence >= candidate['threshold']) == expected)
            for confidence, expected in cases]


def lesson1(root):
    versions = candidates()
    for candidate in versions:
        (root / (candidate['version'] + '.json')).write_text(json.dumps(candidate), encoding='utf-8')
    assert len(versions) == 5
    assert all(set(c) == {'version', 'threshold', 'hypothesis'} for c in versions)
    print('PASS 5 versioned candidates; editable space excludes evaluator and deployment policy')


def lesson2(root):
    development = [(0.1, False), (0.35, False), (0.6, True), (0.8, True)]
    selection = [(0.3, False), (0.45, False), (0.65, True), (0.95, True)]
    eligible = [c for c in candidates() if sum(score(c, development)) >= 3]
    selected = max(eligible, key=lambda c: (sum(score(c, selection)), -c['threshold']))
    frozen = json.loads(json.dumps(selected))
    # Reserved cases are accessed only after the selected version is fixed.
    reserved = [(0.49, False), (0.51, True), (0.85, True), (0.15, False)]
    baseline = candidates()[0]
    before = score(baseline, reserved); after = score(frozen, reserved)
    gains = sum(a == 1 and b == 0 for b, a in zip(before, after))
    regressions = sum(a == 0 and b == 1 for b, a in zip(before, after))
    assert frozen['version'] == 'v3'
    assert sum(after) == 4 and gains == 1 and regressions == 0
    print(json.dumps({'selected': frozen, 'reserved_baseline': before,
        'reserved_selected': after, 'gains': gains, 'regressions': regressions,
        'fixture_cost_calls': 0, 'deterministic_variation': 0}))


def lesson3(root):
    evaluator = root / 'evaluator.txt'
    evaluator.write_text('critical regression blocks promotion', encoding='utf-8')
    original = hashlib.sha256(evaluator.read_bytes()).hexdigest()
    proposed = {'version': 'v6', 'edits': ['evaluator.txt']}
    def admit(candidate):
        allowed = {'threshold.json', 'prompt.txt', 'skill.txt'}
        return (isinstance(candidate.get('edits'), list) and bool(candidate['edits'])
                and all(path in allowed for path in candidate['edits']))
    assert not admit(proposed)  # admission rejects; no edit is applied
    assert admit({'version': 'v7', 'edits': ['threshold.json']})
    assert hashlib.sha256(evaluator.read_bytes()).hexdigest() == original
    history = [{'active': 'v1', 'event': 'initial'}]
    history.append({'active': 'v3', 'event': 'promoted', 'evaluator_digest': original})
    alert = True
    if alert:
        history.append({'active': 'v1', 'event': 'rollback', 'reason': 'simulated critical alert'})
    assert history[-1]['active'] == 'v1'
    print('PASS evaluator edit rejected; compatible pointer v1 -> v3 -> v1 audited')


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--lesson', choices=['1', '2', '3', 'all'], default='all')
    args = parser.parse_args()
    with tempfile.TemporaryDirectory(prefix='academy-w16-') as folder:
        for number, function in enumerate([lesson1, lesson2, lesson3], 1):
            if args.lesson in ('all', str(number)):
                function(Path(folder))


if __name__ == '__main__':
    main()
