"""Detect anomalies in a long-format indicator file and prepare their explanation.

Purpose: run the detection suite (`ai4data.anomaly.detection`) on a CSV file with
one row per indicator, geography, and year, and write the files that the next
steps read: the full detections table, the flagged observations, the shortlist
of series to explain, the batch file of explanation requests, and a run record.

Usage:
    python detect_and_shortlist.py indicator_panel.csv --outdir run1
    python detect_and_shortlist.py data.csv --methods zscore,hampel,capa --min-count 2

Requires ai4data[anomaly] (pandas, scikit-learn, scipy, statsmodels).

Exit status: 0 when the run completed, including a run that flagged nothing;
1 when the input cannot be read or lacks the required columns. A shortlist
that is empty is reported on the standard error stream, writes no batch file, and
removes the batch file and its sidecar left in the folder by an earlier run.

What this does not check: whether a flag is an error. The script finds
observations that are unusual within their own series; it does not check the
source of the data, the unit of the indicator, or whether a flagged value is
true. It does not call a language model; the batch file is the input of a
separate step, and only yearly data can be explained.
"""

import argparse
import hashlib
import json
import sys
from importlib import metadata
from pathlib import Path

import pandas as pd

from ai4data.anomaly.detection import DEFAULT_METHODS, detect_anomalies

# The defaults of capa and isotree flag a large share of short, standardised
# series, so the example uses these settings, which flag about 5% of observations.
DEMO_PARAMS = {
    "capa": {"robust_scale": True, "beta": 25, "beta_tilde": 18},
    "isotree": {"threshold": 0.65},
}
REQUIRED = ["indicator_id", "geography_id", "period", "value"]
FLAG_COLUMNS = [
    "indicator_id",
    "geography_id",
    "period",
    "value",
    "zscore",
    "outlier_count",
    "anomaly_score",
]


def sha256(path: Path) -> str:
    """Return the SHA-256 checksum of a file.

    Parameters
    ----------
    path : Path
        File to read.

    Returns
    -------
    str
        Hexadecimal digest.
    """
    return hashlib.sha256(path.read_bytes()).hexdigest()


def main(argv: list[str] | None = None) -> int:
    """Run detection and write the output files.

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

    Returns
    -------
    int
        Zero when the run completed.
    """
    parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
    parser.add_argument("input", type=Path, help="CSV file in long format")
    parser.add_argument("--outdir", type=Path, default=Path("run"))
    parser.add_argument(
        "--methods",
        default=",".join(DEFAULT_METHODS),
        help="comma-separated detection methods",
    )
    parser.add_argument(
        "--params",
        default=json.dumps(DEMO_PARAMS),
        help="JSON with the options of each method",
    )
    parser.add_argument(
        "--min-count",
        type=int,
        default=3,
        help="methods that must flag an observation for its series to be explained",
    )
    parser.add_argument("--provider", default="openai")
    parser.add_argument(
        "--top",
        type=int,
        default=0,
        help="print this many of the most flagged observations with their methods",
    )
    args = parser.parse_args(argv)

    try:
        df = pd.read_csv(args.input)
        params = json.loads(args.params)
    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

    methods = args.methods.split(",")
    params = {m: p for m, p in params.items() if m in methods}
    result = detect_anomalies(df, mapping="auto", methods=methods, params=params)
    args.outdir.mkdir(parents=True, exist_ok=True)
    result.to_csv(args.outdir / "detections.csv")
    flagged = result.flagged(1)
    flagged[FLAG_COLUMNS].to_csv(args.outdir / "flagged.csv", index=False)
    shortlist = result.shortlist(args.min_count)
    shortlist.to_csv(args.outdir / "shortlist.csv", index=False)

    requests = 0
    if shortlist.empty:
        # A batch file and its sidecar from an earlier run in this folder would be read as requests for these detections.
        for stale in (
            args.outdir / "batch.jsonl",
            args.outdir / "batch_custom_id_map.json",
        ):
            stale.unlink(missing_ok=True)
        print("The shortlist is empty; no batch file written.", file=sys.stderr)
    else:
        _, requests = result.build_explanation_batch(
            args.outdir / "batch.jsonl",
            provider=args.provider,
            min_outlier_count=args.min_count,
        )

    summary = result.summary()
    record = {
        "input": args.input.name,
        "input_sha256": sha256(args.input),
        "library_version": metadata.version("ai4data"),
        "methods": methods,
        "params": params,
        "min_count": args.min_count,
        "summary": summary,
        "shortlisted_series": len(shortlist),
        "batch_requests": requests,
    }
    (args.outdir / "run_record.json").write_text(
        json.dumps(record, indent=2) + "\n", encoding="utf-8"
    )

    rate = 100 * summary["flagged_observations"] / summary["observations"]
    print(
        f"{summary['series']} series, {summary['observations']} observations "
        f"({summary['imputed_observations']} imputed)"
    )
    print(
        f"flagged by at least one method: {summary['flagged_observations']} ({rate:.1f}%)"
    )
    print(
        "flags by method: "
        + ", ".join(f"{m} {n}" for m, n in summary["flagged_by_method"].items())
    )
    print(f"shortlist at {args.min_count} methods: {len(shortlist)} series")
    print(f"batch requests: {requests}")
    if args.top:
        print("\nmost flagged observations:")
        for _, row in flagged.head(args.top).iterrows():
            names = [m for m in methods if row[f"outlier_{m}"]]
            print(
                f"  {row['indicator_id']} {row['geography_id']} {int(row['period'])} "
                f"value {row['value']:.2f} z {row['zscore']:+.2f} "
                f"methods {row['outlier_count']}: {', '.join(names)}"
            )
    return 0


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