#!/usr/bin/env python3
"""Synthetic paired AI workflow lab. Python 3; standard library only.

These invented observations teach arithmetic, not AI performance or safety.
Run: python3 ai-evaluation-lab.py --threshold 0.8 --routine-share 0.8
Export the embedded fixture: python3 ai-evaluation-lab.py --csv > cases.csv
Times are elapsed minutes. Stages are sequential and mutually exclusive.
Every final outcome is assumed accepted after correction/fallback. Draft errors
are observed BEFORE review; this does not estimate errors escaping review.
score is a synthetic routing signal, NOT a probability of correctness.
"""

import argparse
import csv
import random
import statistics
import sys

COLUMNS = 'id,slice,baseline,setup,review,correction,fallback,score,draft_error'.split(',')
DATA = [
    ('A', 'routine', 8, .5, 2, 0, 0, .98, 'none'),
    ('B', 'routine', 10, .5, 3, 1, 0, .91, 'minor'),
    ('C', 'routine', 12, .5, 3, 6, 0, .88, 'major'),
    ('D', 'routine', 9, .5, 2, 0, 0, .85, 'none'),
    ('E', 'exception', 15, .5, 4, 0, 15, .72, 'major'),
    ('F', 'exception', 7, .5, 2, 0, 0, .82, 'none'),
    ('G', 'exception', 11, .5, 3, 7, 0, .95, 'severe'),
    ('H', 'exception', 14, .5, 4, 0, 14, .61, 'major'),
]
CASES = [dict(zip(COLUMNS, row)) for row in DATA]


def assisted_time(case, threshold):
    # Scoring/setup is paid on EVERY case, including those routed to baseline.
    if case['score'] < threshold:
        return case['setup'] + case['baseline']
    return sum(case[key] for key in ('setup', 'review', 'correction', 'fallback'))


def summary(threshold):
    routed = [case for case in CASES if case['score'] >= threshold]
    return {
        'threshold': threshold,
        'coverage': len(routed) / len(CASES),
        'minutes': sum(assisted_time(case, threshold) for case in CASES),
        'draft_errors': sum(case['draft_error'] != 'none' for case in routed),
        'severe_drafts': sum(case['draft_error'] == 'severe' for case in routed),
        'routed': len(routed),
    }


def bootstrap_interval(differences, repetitions=20000):
    # Paired percentile bootstrap: case is resampling unit. In real data,
    # resample independent groups instead when cases share a customer/source.
    rng = random.Random(42)
    means = sorted(statistics.mean(rng.choices(differences, k=len(differences)))
                   for _ in range(repetitions))
    return means[int(.025 * repetitions)], means[int(.975 * repetitions)]


def unit_interval(value):
    number = float(value)
    if not 0 <= number <= 1:
        raise argparse.ArgumentTypeError('must be between 0 and 1')
    return number


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--threshold', type=unit_interval, default=0)
    parser.add_argument('--routine-share', type=unit_interval, default=.8)
    parser.add_argument('--csv', action='store_true')
    args = parser.parse_args()
    if args.csv:
        writer = csv.DictWriter(sys.stdout, fieldnames=COLUMNS)
        writer.writeheader()
        writer.writerows(CASES)
        return
    print('SYNTHETIC TEACHING DATA — not an estimate of production performance.')
    print('Case  baseline  assisted  saved (elapsed minutes)')
    differences = []
    for case in CASES:
        assisted = assisted_time(case, args.threshold)
        difference = case['baseline'] - assisted
        differences.append(difference)
        print(f"{case['id']:>4} {case['baseline']:9.1f} {assisted:9.1f} {difference:6.1f}")
    baseline = sum(case['baseline'] for case in CASES)
    selected = summary(args.threshold)
    print(f"Total: baseline {baseline:.1f}; assisted {selected['minutes']:.1f}; "
          f"saved {baseline - selected['minutes']:.1f} minutes")
    low, high = bootstrap_interval(differences)
    print(f'Paired mean saving {statistics.mean(differences):.2f} min/case; '
          f'illustrative 95% percentile interval [{low:.2f}, {high:.2f}]')
    weighted_saving = 0
    for label, weight in [('routine', args.routine_share),
                          ('exception', 1 - args.routine_share)]:
        rows = [case for case in CASES if case['slice'] == label]
        mean_saving = statistics.mean(case['baseline'] - assisted_time(case, args.threshold)
                                      for case in rows)
        weighted_saving += weight * mean_saving
        print(f'{label}: mean saved {mean_saving:.2f} min; target weight {weight:.0%}')
    print(f'Weighted mean saved: {weighted_saving:.2f} min/case')
    print('\nRouting sweep (illustration, NOT threshold selection on held-out data):')
    print('threshold  coverage  total_min  draft_errors/routed  severe_drafts')
    for threshold in [0, .8, .9, .96, 1]:
        result = summary(threshold)
        print(f"{threshold:9.2f} {result['coverage']:8.1%} {result['minutes']:10.1f} "
              f"{result['draft_errors']:12}/{result['routed']:<6} {result['severe_drafts']:6}")
    print('All final cases accepted by assumption; zero escaped errors here proves nothing.')


if __name__ == '__main__':
    main()
