#!/usr/bin/env python3
"""
Evaluation script for semantic segmentation for dronescapes. Outputs F1Score and mIoU for the classes and each frame.
Usage: ./evaluate_semantic_segmentation.py y_dir gt_dir --classes C1 .. Cn [--class_weights W1 .. Wn] -o results.csv
"""
import sys
import os
from loggez import loggez_logger as logger
from pathlib import Path
from argparse import ArgumentParser, Namespace
from tempfile import TemporaryDirectory
from multiprocessing import Pool
from functools import partial
from torchmetrics.functional.classification import multiclass_stat_scores
from tqdm import tqdm
import torch as tr
import numpy as np
import pandas as pd

sys.path.append(Path(__file__).parents[1].__str__())
from dronescapes_reader import MultiTaskDataset
from dronescapes_reader.dronescapes_representations import SemanticRepresentation

def compute_metrics(tp: np.ndarray, fp: np.ndarray, tn: np.ndarray, fn: np.ndarray) -> pd.DataFrame:
    precision = tp / (tp + fp)
    recall = tp / (tp + fn)
    f1 = 2 * precision * recall / (precision + recall)
    iou = tp / (tp + fp + fn)
    return pd.DataFrame([precision, recall, f1, iou], index=["precision", "recall", "f1", "iou"]).T

def compute_metrics_by_class(df: pd.DataFrame, class_name: str) -> pd.DataFrame:
    df = df.query("class_name == @class_name").drop(columns="class_name")
    df.loc["all"] = df.sum()
    df[["precision", "recall", "f1", "iou"]] = compute_metrics(df["tp"], df["fp"], df["tn"], df["fn"])
    df.insert(0, "class_name", class_name)
    df = df.fillna(0).round(3)
    return df

def _do_one(i: int, reader: MultiTaskDataset, num_classes: int) -> tuple[tr.Tensor, str]:
    data, name = reader[i][0:2]
    y = data["pred"].argmax(-1) if data["pred"].dtype != tr.int64 else data["pred"]
    gt = data["gt"].argmax(-1) if data["gt"].dtype != tr.int64 else data["gt"]
    return multiclass_stat_scores(y, gt, num_classes=num_classes, average=None)[:, 0:4], name

def compute_raw_stats_per_frame(reader: MultiTaskDataset, classes: list[str], n_workers: int = 1) -> pd.DataFrame:
    res = tr.zeros((len(reader), len(classes), 4)).long() # (N, NC, 4)

    map_fn = map if n_workers == 1 else Pool(n_workers).imap
    do_one_fn = partial(_do_one, reader=reader, num_classes=len(classes))
    map_res = list(tqdm(map_fn(do_one_fn, range(len(reader))), total=len(reader)))
    res, index = tr.stack([x[0] for x in map_res]).reshape(len(reader) * len(classes), 4), [x[1] for x in map_res]

    df = pd.DataFrame(res, index=np.repeat(index, len(classes)), columns=["tp", "fp", "tn", "fn"])
    df.insert(0, "class_name", np.array(classes)[:, None].repeat(len(index), 1).T.flatten())
    return df

def compute_final_per_scene(res: pd.DataFrame, scene: str, classes: list[str],
                            class_weights: list[float]) -> tuple[float, float]:
    df = res.iloc[[x.startswith(scene) for x in res.index]]
    # aggregate for this class all the individual predictions
    df_scene = df[["class_name", "tp", "fp", "tn", "fn"]].groupby("class_name") \
        .apply(lambda x: x.sum(), include_groups=False).loc[classes]
    df_metrics = compute_metrics(df_scene["tp"], df_scene["fp"], df_scene["tn"], df_scene["fn"])
    iou_weighted = (df_metrics["iou"] * class_weights).sum()
    f1_weighted = (df_metrics["f1"] * class_weights).sum()
    return scene, iou_weighted, f1_weighted

def _check_and_symlink_dirs(y_dir: Path, gt_dir: Path) -> Path:
    """checks whether the two provided paths are actual full of npz directories and links them together in a tmp dir"""
    assert (l := {x.name for x in y_dir.iterdir()}) == (r := {x.name for x in gt_dir.iterdir()}), f"{l} \n vs \n {r}"
    assert all(x.endswith(".npz") for x in [*l, *r]), f"Not dirs of only .npz files: {l} \n {r}"
    (temp_dir := Path(TemporaryDirectory().name)).mkdir(exist_ok=False)
    os.symlink(y_dir, temp_dir / "pred")
    os.symlink(gt_dir, temp_dir / "gt")
    return temp_dir

def get_args() -> Namespace:
    parser = ArgumentParser()
    parser.add_argument("y_dir", type=lambda p: Path(p).absolute())
    parser.add_argument("gt_dir", type=lambda p: Path(p).absolute())
    parser.add_argument("--output_path", "-o", type=Path, required=True)
    parser.add_argument("--classes", required=True, nargs="+")
    parser.add_argument("--class_weights", nargs="+", type=float)
    parser.add_argument("--scenes", nargs="+", default=["all"], help="each scene will get separate metrics if provided")
    parser.add_argument("--overwrite", action="store_true")
    parser.add_argument("--n_workers", type=int, default=1)
    args = parser.parse_args()
    if args.class_weights is None:
        logger.info("No class weights provided, defaulting to equal weights.")
        args.class_weights = [1 / len(args.classes)] * len(args.classes)
    assert (a := len(args.class_weights)) == (b := len(args.classes)), (a, b)
    assert np.fabs(sum(args.class_weights) - 1) < 1e-3, (args.class_weights, sum(args.class_weights))
    assert args.output_path.suffix == ".csv", f"Prediction file must end in .csv, got: '{args.output_path.suffix}'"
    if len(args.scenes) > 0:
        logger.info(f"Scenes: {args.scenes}")
    if args.output_path.exists() and args.overwrite:
        os.remove(args.output_path)
    assert args.n_workers >= 1 and isinstance(args.n_workers, int), args.n_workers
    return args

def main(args: Namespace):
    # setup to put both directories in the same parent directory for the reader to work.
    temp_dir = _check_and_symlink_dirs(args.y_dir, args.gt_dir)
    pred_repr = SemanticRepresentation("pred", classes=args.classes, color_map=[[0, 0, 0]] * len(args.classes))
    gt_repr = SemanticRepresentation("gt", classes=args.classes, color_map=[[0, 0, 0]] * len(args.classes))
    reader = MultiTaskDataset(temp_dir, task_names=["pred", "gt"], task_types={"pred": pred_repr, "gt": gt_repr},
                              handle_missing_data="drop", normalization=None)
    assert (a := len(reader.files_per_repr["gt"])) == (b := len(reader.files_per_repr["pred"])), f"{a} vs {b}"

    # Compute TP, FP, TN, FN for each frame
    raw_stats = compute_raw_stats_per_frame(reader, args.classes, args.n_workers)
    logger.info(f"Stored raw metrics file to: '{args.output_path}'")
    Path(args.output_path).parent.mkdir(exist_ok=True, parents=True)
    raw_stats.to_csv(args.output_path)

    # Compute Precision, Recall, F1, IoU for each class and put them together in the same df.
    metrics_per_class = pd.concat([compute_metrics_by_class(raw_stats, class_name) for class_name in args.classes])

    # Aggregate the class-level metrics to the final metrics based on the class weights (compute globally by stats)
    final_agg = []
    for scene in args.scenes: # if we have >1 scene in the test set, aggregate the results for each of them separately
        final_agg.append(compute_final_per_scene(metrics_per_class, scene, args.classes, args.class_weights))
    final_agg = pd.DataFrame(final_agg, columns=["scene", "iou", "f1"]).set_index("scene")
    if len(args.scenes) > 1:
        final_agg.loc["mean"] = final_agg.mean()
    final_agg = (final_agg * 100).round(3)
    print(final_agg)

if __name__ == "__main__":
    main(get_args())