"""Synthetic confidence audit; Python standard library only. No model/API calls."""
import csv
import hashlib
import json
import math
import pathlib
import platform
from collections import defaultdict


def summarize(rows, threshold=0.9, bins=10):
    if not rows:
        raise ValueError('at least one labelled row is required')
    if not isinstance(bins, int) or isinstance(bins, bool) or bins <= 0:
        raise ValueError('bins must be a positive integer')
    if not math.isfinite(threshold) or not 0 <= threshold <= 1:
        raise ValueError('threshold must be finite and within [0, 1]')
    groups = defaultdict(list)
    for confidence, correct in rows:
        if not math.isfinite(confidence) or not 0 <= confidence <= 1:
            raise ValueError('confidence must be finite and within [0, 1]')
        if correct not in (0, 1):
            raise ValueError('correct must be 0 or 1')
        # Left-closed equal-width bins; 1.0 belongs to the final bin.
        groups[min(int(confidence * bins), bins - 1)].append((confidence, correct))
    n = len(rows)
    selected = [(p, y) for p, y in rows if p >= threshold]
    errors = sum(1 - y for _, y in selected)
    buckets = []
    for index, values in sorted(groups.items()):
        buckets.append({'index': index, 'count': len(values),
                        'mean_confidence': sum(p for p, _ in values) / len(values),
                        'accuracy': sum(y for _, y in values) / len(values)})
    return {'count': n, 'accuracy': sum(y for _, y in rows) / n,
            'brier': sum((p - y) ** 2 for p, y in rows) / n,
            'ece': sum(b['count'] / n * abs(b['mean_confidence'] - b['accuracy']) for b in buckets),
            'threshold': threshold, 'selected_count': len(selected),
            'coverage': len(selected) / n, 'selected_errors': errors,
            'selected_error_rate': errors / len(selected) if selected else None,
            'bins': buckets}


def load_fixture(path):
    profiles = defaultdict(list)
    with path.open(newline='', encoding='utf-8') as stream:
        reader = csv.DictReader(stream)
        if reader.fieldnames != ['profile', 'case_id', 'confidence', 'correct']:
            raise ValueError('unexpected CSV columns')
        seen = set()
        for row in reader:
            key = (row['profile'], row['case_id'])
            if key in seen:
                raise ValueError('duplicate profile/case ID')
            seen.add(key)
            profiles[row['profile']].append((float(row['confidence']), int(row['correct'])))
    return profiles


def main():
    path = pathlib.Path(__file__).with_name('fixture.csv')
    report = {'kind': 'synthetic arithmetic demonstration; not an LLM benchmark',
              'original_demo_date_kst': '2026-10-24', 'python': platform.python_version(),
              'fixture_sha256': hashlib.sha256(path.read_bytes()).hexdigest(),
              'bin_rule': '10 equal-width left-closed bins; final bin includes 1.0',
              'profiles': {name: summarize(rows) for name, rows in load_fixture(path).items()}}
    print(json.dumps(report, ensure_ascii=False, indent=2, allow_nan=False))


if __name__ == '__main__':
    main()
