"""Summarise the reviewers' decisions against the review file.

Purpose: read the review file that `review_export.py` wrote and the feedback
that the review application exports as CSV, and report how many items have a
verdict, how many are still unreviewed, and which items a reviewer wants
followed up. The report is the record that a review cycle is complete.

Usage:
    python review_summary.py run1/review.json feedback_example.csv

Requires pandas. Exit status: 0 when every item has a verdict; 1 when a file
cannot be read or lacks the expected columns; 2 when some items have no verdict.

What this does not check: the quality of the verdicts. The script counts
decisions. It does not compare reviewers, and it does not check that a
suggested classification is right.
"""

import argparse
import json
import sys
from pathlib import Path

import pandas as pd

NEEDED = ["indicator_code", "geography_code", "window_str", "verdict"]


def main(argv: list[str] | None = None) -> int:
    """Print the review status.

    Parameters
    ----------
    argv : list[str] | None, optional
        Command arguments, or the process arguments when omitted.

    Returns
    -------
    int
        Zero when every item has a verdict.
    """
    parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
    parser.add_argument("review", type=Path)
    parser.add_argument("feedback", type=Path)
    args = parser.parse_args(argv)
    try:
        items = json.loads(args.review.read_text(encoding="utf-8"))["items"]
        feedback = pd.read_csv(args.feedback)
        feedback[NEEDED]
    except (OSError, KeyError, ValueError) as error:
        print(f"Cannot read the inputs: {error}", file=sys.stderr)
        return 1

    # A resubmitted verdict replaces the earlier one for the same item.
    feedback = feedback.drop_duplicates(NEEDED[:3], keep="last")
    decided = {
        (r.indicator_code, r.geography_code, r.window_str): r
        for r in feedback.itertuples()
    }
    keys = [(i["indicator_code"], i["geography_code"], i["window_str"]) for i in items]
    open_items = [k for k in keys if k not in decided]
    print(f"items in the review file: {len(keys)}")
    print(f"items with a verdict: {len(keys) - len(open_items)}")
    counts = pd.Series([decided[k].verdict for k in keys if k in decided])
    for verdict, number in counts.value_counts().sort_index().items():
        print(f"  {verdict}: {number}")
    follow_up = [
        k for k in keys if k in decided and decided[k].verdict == "needs_review"
    ]
    print("to follow up:")
    for key in follow_up:
        row = decided[key]
        suggestion = row.suggested_classification
        suffix = f" (suggested: {suggestion})" if isinstance(suggestion, str) else ""
        print(f"  {key[0]} {key[1]} {key[2]}{suffix}")
    print("without a verdict:")
    for key in open_items:
        print(f"  {key[0]} {key[1]} {key[2]}")
    return 2 if open_items else 0


if __name__ == "__main__":
    raise SystemExit(main())
