"""Append one synthetic record to a copy of the tutorial file.

Run: python append_netcdf.py example.nc example-appended.nc
The source is unchanged and an existing output will not be overwritten.
"""
from datetime import timedelta
from pathlib import Path
import shutil
from netCDF4 import Dataset, date2num, num2date


def append_example(source="example.nc", output="example-appended.nc"):
    with open(source, "rb") as src, open(output, "xb") as dst:
        shutil.copyfileobj(src, dst)
    with Dataset(output, "r+") as ds:
        time = ds.variables["time"]
        temp = ds.variables["temperature"]
        assert ds.dimensions["time"].isunlimited()
        n = len(ds.dimensions["time"])
        last_date = num2date(time[n - 1], time.units, calendar=time.calendar)
        next_date = last_date + timedelta(hours=6)
        next_slice = temp[n - 1, :, :] + 0.5
        # Both the new time coordinate and the data record must be written.
        time[n] = date2num(next_date, time.units, calendar=time.calendar)
        temp[n, :, :] = next_slice
    print(f"Appended one record to {output}; {source} is unchanged")
    return Path(output)


if __name__ == "__main__":
    import argparse
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("source", nargs="?", default="example.nc")
    parser.add_argument("output", nargs="?", default="example-appended.nc")
    args = parser.parse_args()
    append_example(args.source, args.output)
