import os
import os.path as osp

from human_cver.files.json_file import load_json
from ..files import save_json
from ..tools import Logger

def get_loss(log_filename:str)-> dict:
    loss_dict = dict()
    Logger.info(f"analyze: {log_filename}")
    with open(log_filename, "r") as fr:
        seg = "] epoch="
        for line in fr.readlines():
            if seg not in line:
                continue

            d = dict()
            t = line.split(seg)[0].split(" ")[1:3]
            d["time"] = "20" + t[0] + " " + t[1]
            parts = line.split(seg)[1].strip().split(",")
            epoch = int(parts[0].strip())
            for x in parts[1:]:
                k, v = x.strip().split("=")
                d[k] = float(v)
            loss_dict[epoch] = d
    return loss_dict

def make_table() -> None:
    total_dict = dict()
    for root, _, fns in os.walk("logs"):
        if "train.log" in fns:
            exp_name = root[len("logs/"):]
            loss_dict = get_loss(osp.join(root, "train.log"))

            info = dict()
            if osp.exists(osp.join(root, "exp_info.json")):
                info = load_json(osp.join(root, "exp_info.json"))
            total_dict[exp_name] = {
                "info": info,
                "loss": loss_dict
            }

    save_json("table.json", total_dict)
