"""Tally fictional original labels separately from worked adjudication labels."""
import argparse
import csv
import json
from collections import Counter
from fractions import Fraction
from pathlib import Path

LABELS = ('action', 'information', 'unclear')


def read_csv(path):
    with Path(path).open(encoding='utf-8-sig', newline='') as handle:
        return list(csv.DictReader(handle))


def validate_ids(rows):
    ids = [row['id'] for row in rows]
    if not ids or len(ids) != len(set(ids)) or any(not item for item in ids):
        raise ValueError('IDs must be nonempty and unique.')
    return set(ids)


def evaluate(annotation_path, adjudication_path):
    rows = read_csv(annotation_path)
    ids = validate_ids(rows)
    final = read_csv(adjudication_path)
    if validate_ids(final) != ids:
        raise ValueError('Adjudication must contain exactly the original case IDs.')
    for row in rows:
        if row['annotator_a'] not in LABELS or row['annotator_b'] not in LABELS:
            raise ValueError('Every original label must be action, information, or unclear.')
    if any(row['final_label'] not in LABELS or not row['reason'].strip() for row in final):
        raise ValueError('Each final label needs a valid label and a written reason.')
    count = len(rows)
    matrix = {a: {b: 0 for b in LABELS} for a in LABELS}
    a_counts = Counter(row['annotator_a'] for row in rows)
    b_counts = Counter(row['annotator_b'] for row in rows)
    for row in rows:
        matrix[row['annotator_a']][row['annotator_b']] += 1
    agreements = sum(matrix[label][label] for label in LABELS)
    observed = Fraction(agreements, count)
    expected = sum((Fraction(a_counts[label] * b_counts[label], count * count)
                    for label in LABELS), Fraction())
    kappa = (observed - expected) / (1 - expected) if expected != 1 else None
    final_by_id = {row['id']: row['final_label'] for row in final}
    final_counts = Counter(final_by_id.values())
    return {
        'scope': 'Fictional annotation columns, not collected human agreement or accuracy.',
        'cases': count,
        'label_order': list(LABELS),
        'original_matrix_rows_a_columns_b': matrix,
        'a_marginals': {label: a_counts[label] for label in LABELS},
        'b_marginals': {label: b_counts[label] for label in LABELS},
        'original_agreements': agreements,
        'original_disagreement_ids': sorted(row['id'] for row in rows if row['annotator_a'] != row['annotator_b']),
        'observed_agreement_exact': str(observed),
        'observed_agreement_percent': float(observed * 100),
        'expected_agreement_exact': str(expected),
        'cohen_kappa_exact': None if kappa is None else str(kappa),
        'cohen_kappa_decimal': None if kappa is None else float(kappa),
        'worked_adjudication': {
            'final_counts': {label: final_counts[label] for label in LABELS},
            'differs_from_a_ids': sorted(row['id'] for row in rows if final_by_id[row['id']] != row['annotator_a']),
            'differs_from_b_ids': sorted(row['id'] for row in rows if final_by_id[row['id']] != row['annotator_b']),
            'independent_post_adjudication_agreement': None,
        },
    }


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('annotations')
    parser.add_argument('adjudication')
    args = parser.parse_args()
    try:
        print(json.dumps(evaluate(args.annotations, args.adjudication), indent=2))
    except (ValueError, KeyError, OSError) as exc:
        parser.exit(2, f'Input error: {exc}\n')
