"""Compare the flags of a run with the anomalies planted in the example panel.

Purpose: the example panel is fictional, and the file `planted_anomalies.csv`
lists the jumps, runs, and constant tails that were put into it. This script
reports, for each planted anomaly, the largest number of methods that flag one
of its observed years, so that the team sees what the methods find and what
they miss on data where the answer is known.

Usage:
    python score_against_planted.py run1/flagged.csv planted_anomalies.csv indicator_panel.csv

Requires pandas. Exit status: 0 after the report; 1 when a file cannot be read
or lacks the expected columns.

What this does not check: how the methods perform on real series. Planted
anomalies are simpler than real ones, the panel is small, and the report counts
a flag anywhere in the planted years as a find.
"""

import argparse
import sys
from pathlib import Path

import pandas as pd

KEY = ["indicator_id", "geography_id"]


def main(argv: list[str] | None = None) -> int:
    """Print one line per planted anomaly and a count by outcome.

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

    Returns
    -------
    int
        Zero after the report.
    """
    parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
    parser.add_argument("flagged", type=Path)
    parser.add_argument("planted", type=Path)
    parser.add_argument("panel", type=Path)
    parser.add_argument("--min-count", type=int, default=3)
    args = parser.parse_args(argv)
    try:
        flagged = pd.read_csv(args.flagged)
        planted = pd.read_csv(args.planted)
        panel = pd.read_csv(args.panel)
        planted[["first_period", "last_period"]]
        flagged[["period", "outlier_count"]]
    except (OSError, KeyError, ValueError) as error:
        print(f"Cannot read the inputs: {error}", file=sys.stderr)
        return 1

    outcomes: dict[str, int] = {}
    for row in planted.itertuples():
        years = range(row.first_period, row.last_period + 1)
        observed = panel[
            (panel["indicator_id"] == row.indicator_id)
            & (panel["geography_id"] == row.geography_id)
            & panel["period"].isin(years)
        ]
        hits = flagged[
            (flagged["indicator_id"] == row.indicator_id)
            & (flagged["geography_id"] == row.geography_id)
            & flagged["period"].isin(years)
        ]
        best = int(hits["outlier_count"].max()) if len(hits) else 0
        if observed.empty:
            outcome = "not in the data"
        elif best >= args.min_count:
            outcome = "found"
        elif best > 0:
            outcome = "weak"
        else:
            outcome = "missed"
        outcomes[outcome] = outcomes.get(outcome, 0) + 1
        print(
            f"{row.indicator_id} {row.geography_id} {row.kind} "
            f"{row.first_period}-{row.last_period}: {outcome} (most methods: {best})"
        )
    print(", ".join(f"{k} {v}" for k, v in sorted(outcomes.items())))
    return 0


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