"""Run with export.xml or the product API's workouts.csv to draw the same chart."""
import argparse
import xml.etree.ElementTree as ET
from pathlib import Path

import matplotlib.pyplot as plt
import pandas as pd


def read_workouts(path):
    if path.suffix.lower() == ".xml":
        starts = []
        for _, element in ET.iterparse(path, events=("end",)):
            if element.tag == "Workout":
                starts.append(element.attrib["startDate"])
            element.clear()
        timestamps = pd.to_datetime(starts, utc=True)
    else:
        starts = pd.read_csv(path, usecols=["start"])["start"]
        timestamps = pd.to_datetime(starts, unit="ms", utc=True)
    return pd.DataFrame({"start": timestamps})


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("input", type=Path)
    parser.add_argument("--time-zone", required=True)
    parser.add_argument("--output", type=Path, default=Path("workout-days.png"))
    args = parser.parse_args()
    workouts = read_workouts(args.input)
    if workouts.empty:
        parser.exit("No workout records in this input.\n")
    days = workouts.start.dt.tz_convert(args.time_zone).dt.date
    counts = days.value_counts().sort_index()
    ax = counts.plot.bar(xlabel="Date", ylabel="Recorded workouts", rot=45)
    ax.figure.tight_layout()
    ax.figure.savefig(args.output)
