import json
from pathlib import Path

import pandas as pd


def load_data(file_path: Path) -> pd.DataFrame:
    file_path = Path(__file__).parent / "points"
    files = file_path.glob("*.jsonl")

    json_data = []
    for file in files:
        with open(file) as f:
            for line in f:
                json_data.append(json.loads(line))

    df = pd.DataFrame(json_data)
    return df


def save_to_markdown(df: pd.DataFrame, file_path: Path) -> None:
    df = df.groupby("GitHub").sum().astype(int)
    # create a new column with the sum of the points
    df["Total"] = df.sum(axis=1)
    # sort the dataframe by the total points
    df = df.sort_values("Total", ascending=False)

    md = df.to_markdown()
    # add title
    md = f"# Points\n\n_Note_: this table is **autogenerated** and should not be edited. It is intended to get an overview of contributions.\n\n {md}"
    with open(file_path, "w") as f:
        f.write(md)


if __name__ == "__main__":
    file_path = Path(__file__).parent / "points"
    save_path = Path(__file__).parent / "points_table.md"

    df = load_data(file_path)
    save_to_markdown(df, save_path)
