"""Add one fictional year to the example panel, to stand in for a new data release.

Purpose: write a copy of `indicator_panel.csv` with a 2025 value for every
series. Each value continues the series by its average yearly change plus a
small random step, and two series receive a planted jump, so that a repeat run
has something new to find.

Usage:
    python extend_panel.py indicator_panel.csv indicator_panel_2025.csv

Requires pandas and numpy. Exit status: 0 when the file was written; 1 when
the input cannot be read.

What this does not check: that the values resemble a real release. They are
invented, and the seed is fixed so that the output is the same on every run.
"""

import argparse
import sys
from pathlib import Path

import numpy as np
import pandas as pd

JUMPS = {("SH.MORT.U5", "BBB"): 12.0, ("SI.POV.HEAD", "FFF"): -10.0}


def main(argv: list[str] | None = None) -> int:
    """Write the extended panel.

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

    Returns
    -------
    int
        Zero when the file was written.
    """
    parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
    parser.add_argument("input", type=Path)
    parser.add_argument("output", type=Path)
    args = parser.parse_args(argv)
    try:
        panel = pd.read_csv(args.input)
    except OSError as error:
        print(f"Cannot read the input: {error}", file=sys.stderr)
        return 1
    rng = np.random.default_rng(2025)
    new_rows = []
    for (indicator, geography), series in panel.groupby(
        ["indicator_id", "geography_id"]
    ):
        series = series.sort_values("period")
        step = series["value"].diff().mean()
        value = series["value"].iloc[-1] + step + rng.normal(0, 1.0)
        value += JUMPS.get((indicator, geography), 0.0)
        row = series.iloc[-1].copy()
        row["period"] = 2025
        row["value"] = round(float(np.clip(value, 0.5, 100)), 2)
        new_rows.append(row)
    out = pd.concat([panel, pd.DataFrame(new_rows)], ignore_index=True)
    out = out.sort_values(["indicator_id", "geography_id", "period"])
    out.to_csv(args.output, index=False)
    print(f"wrote {len(out)} rows to {args.output}")
    return 0


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