"""Week 13: deterministic team contracts; no model calls or generated code execution."""
import argparse
import concurrent.futures
import hashlib
import json
import tempfile
import threading
import time
from pathlib import Path


def lesson1(root):
    tasks = [(2, 3), (4, 5), (7, 1)]
    def worker(pair):
        time.sleep(0.02)  # harmless stand-in for independent waiting
        return sum(pair)
    start = time.perf_counter()
    baseline = [worker(pair) for pair in tasks]
    single_elapsed = time.perf_counter() - start
    start = time.perf_counter()
    with concurrent.futures.ThreadPoolExecutor(max_workers=3) as pool:
        team = list(pool.map(worker, tasks))
    team_elapsed = time.perf_counter() - start
    assert baseline == team == [5, 9, 8]
    print(json.dumps({'fixture_quality': '3/3 each', 'baseline_calls': 3,
        'team_worker_calls': 3, 'team_coordination_messages': 2,
        'baseline_seconds': single_elapsed, 'team_seconds': team_elapsed}))
    print('Timing is measured, not a guaranteed speedup. No model/team-quality claim.')


def lesson2(root):
    path = root / 'artifact.json'
    lock = threading.Lock()
    state = {'version': 1, 'owner': 'implementer', 'value': 22}
    path.write_text(json.dumps(state), encoding='utf-8')
    def update(owner, expected, value):
        with lock:
            current = json.loads(path.read_text(encoding='utf-8'))
            if owner != current['owner'] or expected != current['version']:
                return False
            current.update(version=expected + 1, value=value)
            path.write_text(json.dumps(current), encoding='utf-8')
            return True
    assert update('implementer', 1, 23)
    assert not update('reviewer', 2, 99)
    assert not update('implementer', 1, 99)
    digest = hashlib.sha256(path.read_bytes()).hexdigest()
    receipt = {'reviewed_version': 2, 'sha256': digest, 'accepted': True}
    assert receipt['sha256'] == hashlib.sha256(path.read_bytes()).hexdigest()
    print('PASS version 2; wrong owner and stale writer rejected; review bound to digest')


def lesson3(root):
    rows = [{'amount': 12, 'status': 'paid'}, {'amount': 7, 'status': 'pending'},
            {'amount': 5, 'status': 'paid'}]
    reports = {'agent_a': 24, 'agent_b': 17, 'agent_c': 24}
    verified = sum(row['amount'] for row in rows if row['status'] == 'paid')
    assert verified == 17
    assert sum(value == 24 for value in reports.values()) == 2
    print('PASS paid-only total 17; majority total 24 includes pending 7')


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-w13-') 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()
