"""Read the answers to a batch file and write the review file and a summary.

Purpose: parse the output file of an explanation batch against the detections
table, write the JSON file that the review application opens, and print how the
explanations are distributed. Each item of the review file holds one flagged
window, the explanation, and the series around the window.

Usage:
    python review_export.py run1/detections.csv run1/batch.jsonl run1/batch_output.jsonl \\
        --review run1/review.json

Requires ai4data[anomaly]. Exit status: 0 when at least one explanation was
read and the review file written; 1 when an input cannot be read or no answer
could be parsed.

What this does not check: whether an explanation is correct. The script reads
the structure of the answers and skips a request whose answer does not parse and reports how many requests were answered;
the reviewer decides about every item, and the review application records the
decision.
"""

import argparse
import sys
from pathlib import Path

import pandas as pd

from ai4data.anomaly.explanation import export_for_review, parse_batch_output


def main(argv: list[str] | None = None) -> int:
    """Parse the answers, write the review file, and print the summary.

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

    Returns
    -------
    int
        Zero when the review file was written.
    """
    parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
    parser.add_argument("detections", type=Path)
    parser.add_argument("batch", type=Path)
    parser.add_argument("answers", type=Path)
    parser.add_argument("--review", type=Path, required=True)
    parser.add_argument("--provider", default="openai")
    args = parser.parse_args(argv)
    try:
        table = pd.read_csv(args.detections)
    except OSError as error:
        print(f"Cannot read the detections: {error}", file=sys.stderr)
        return 1
    table["freq"] = "A"
    geography = table.drop_duplicates("geography_id").set_index("geography_id")
    indicator = table.drop_duplicates("indicator_id").set_index("indicator_id")
    try:
        parsed = parse_batch_output(
            args.answers,
            args.provider,
            indicator["indicator_name"].to_dict(),
            geography["geography_name"].to_dict(),
            custom_id_map_path=args.batch.with_name(
                args.batch.stem + "_custom_id_map.json"
            ),
        )
    except (OSError, ValueError) as error:
        print(f"Cannot read the answers: {error}", file=sys.stderr)
        return 1
    if parsed.empty:
        print("No answer could be parsed.", file=sys.stderr)
        return 1

    export_for_review(parsed, timeseries_df=table, output_path=args.review)
    requests = len(args.batch.read_text(encoding="utf-8").splitlines())
    answered = parsed["custom_id"].nunique()
    print(
        f"{answered} of {requests} requests answered, {len(parsed)} explanations read"
    )
    print(f"review file {args.review.name} written")
    for name, column in (
        ("classification", "classification"),
        ("evidence", "evidence_strength"),
    ):
        counts = parsed[column].value_counts()
        print(f"by {name}: " + ", ".join(f"{k} {v}" for k, v in counts.items()))
    return 0


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