"""Compare the flagged observations of two runs of the detection script.

Purpose: when the pipeline is repeated on a new release of the data, list which
flagged observations are new, which persist, and which no longer appear, so
that the reviewer starts with the new ones and the team sees how much the new
data changed the earlier flags.

Usage:
    python compare_runs.py run1/flagged.csv run2/flagged.csv --min-count 3

Requires pandas. Exit status: 0 after the comparison; 1 when a file cannot be
read or lacks the columns indicator_id, geography_id, period, and
outlier_count.

What this does not check: why a flag appeared or disappeared. Detection
standardises each series, so one new year changes the baseline of the whole
series, and an earlier flag can drop out without any earlier value changing.
The script also does not detect revisions of earlier values.
"""

import argparse
import sys
from pathlib import Path

import pandas as pd

KEY = ["indicator_id", "geography_id", "period"]


def keys(path: Path, min_count: int) -> set[tuple]:
    """Return the keys of the observations flagged by enough methods.

    Parameters
    ----------
    path : Path
        A `flagged.csv` file of the detection script.
    min_count : int
        Number of methods that must flag an observation.

    Returns
    -------
    set[tuple]
        Tuples of indicator, geography, and period.
    """
    table = pd.read_csv(path)
    keep = table[table["outlier_count"] >= min_count]
    return set(keep[KEY].itertuples(index=False, name=None))


def main(argv: list[str] | None = None) -> int:
    """Print the new, persisting, and resolved flags.

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

    Returns
    -------
    int
        Zero after the comparison.
    """
    parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
    parser.add_argument("earlier", type=Path)
    parser.add_argument("later", type=Path)
    parser.add_argument("--min-count", type=int, default=3)
    args = parser.parse_args(argv)
    try:
        before = keys(args.earlier, args.min_count)
        after = keys(args.later, args.min_count)
    except (OSError, KeyError) as error:
        print(f"Cannot compare the files: {error}", file=sys.stderr)
        return 1
    print(
        f"flags at {args.min_count} methods or more: "
        f"{len(before)} earlier, {len(after)} later"
    )
    print(f"persisting: {len(before & after)}")
    for label, group in (
        ("new", after - before),
        ("no longer flagged", before - after),
    ):
        print(f"{label}: {len(group)}")
        for indicator, geography, period in sorted(group):
            print(f"  {indicator} {geography} {period}")
    return 0


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