"""Prepare indicator series for detection and report what the preparation did.

Purpose: run the preparation step of the detection suite (gap filling,
imputation, trend removal, and standardisation) on a long-format CSV file, print
what changed, and optionally show one series before and after. The report is
the check that the series can be compared on one scale before any method runs.

Usage:
    python prepare_series.py indicator_panel.csv
    python prepare_series.py indicator_panel.csv --series EG.ELC.ACCS FFF --years 2005 2009
    python prepare_series.py indicator_panel.csv --impute-method locf --output prepared.csv

Requires ai4data[anomaly]. Exit status: 0 when every series was prepared;
1 when the input cannot be read or lacks the required columns; 2 when a series
was dropped for having too few observed values (the others are still reported).

What this does not check: whether the imputed values are plausible, or whether
a trend that was removed is a real change of level. Preparation treats a
permanent shift of level like any other trend, and the report does not judge it.
"""

import argparse
import sys
from pathlib import Path

import pandas as pd

from ai4data.anomaly.detection import normalize

REQUIRED = ["indicator_id", "geography_id", "period", "value"]


def main(argv: list[str] | None = None) -> int:
    """Prepare the series and print the report.

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

    Returns
    -------
    int
        Zero when every series was prepared.
    """
    parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
    parser.add_argument("input", type=Path)
    parser.add_argument("--impute-method", default="interpolation")
    parser.add_argument("--series", nargs=2, metavar=("INDICATOR", "GEOGRAPHY"))
    parser.add_argument("--years", nargs=2, type=int, default=[2000, 2024])
    parser.add_argument("--output", type=Path)
    args = parser.parse_args(argv)
    try:
        df = pd.read_csv(args.input)
    except (OSError, ValueError) as error:
        print(f"Cannot read the input: {error}", file=sys.stderr)
        return 1
    missing = [c for c in REQUIRED if c not in df.columns]
    if missing:
        print(f"Missing columns: {', '.join(missing)}", file=sys.stderr)
        return 1

    prepared = normalize(df, "auto", impute_method=args.impute_method)
    info = prepared.attrs
    dropped = info.get("dropped_series", [])
    keys = ["indicator_id", "geography_id"]
    print(
        f"rows read: {len(df)}; rows after gap filling: {len(prepared)}; "
        f"series: {prepared.groupby(keys).ngroups}"
    )
    print(
        f"gaps filled: {info.get('total_gaps')}; "
        f"imputed observations: {int(prepared['is_imputed'].sum())} "
        f"({args.impute_method})"
    )
    print(f"series dropped for too few observations: {len(dropped)}")

    scale = prepared.groupby("indicator_id").agg(
        value_min=("value", "min"),
        value_max=("value", "max"),
        zscore_min=("zscore", "min"),
        zscore_max=("zscore", "max"),
    )
    print("scale of each indicator, before and after standardising:")
    print(scale.round(1).to_string())

    if args.series:
        indicator, geography = args.series
        one = prepared[
            (prepared["indicator_id"] == indicator)
            & (prepared["geography_id"] == geography)
            & prepared["period"].between(*args.years)
        ]
        print(f"\n{indicator} {geography}, {args.years[0]}-{args.years[1]}:")
        columns = ["period", "value", "is_imputed", "zscore"]
        print(one[columns].round(2).to_string(index=False))

    if args.output:
        prepared.to_csv(args.output, index=False)
        print(f"\nwrote {args.output}")
    return 2 if dropped else 0


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