import os
import argparse

import numpy as np
from tqdm import tqdm

from preprocess import preprocess


class WrapRunner(object):

    def __init__(self, runner, rbo_mode, id=None):
        self.runner = runner
        self.rbo_mode = rbo_mode
        self.id = id
    
    def __call__(self, *args):
        if self.rbo_mode:
            inputs = list(args)
            for i in range(len(inputs)):
                if not isinstance(inputs[i], np.ndarray):
                    inputs[i] = inputs[i].numpy()
            outs = self.runner.inference(self.id, inputs)
            if isinstance(outs, list) and len(outs) == 1:
                return outs[0]
            return outs
        else:
            outs = self.runner.run(*args, as_numpy=True)
            return outs

    def close(self):
        if self.rbo_mode:
            self.runner.remove_model(self.id)


def init_runner(args):
    suffix = os.path.splitext(args.model_file)[1]
    print(f"INFO: Load model from {args.model_file}")
    if suffix == '.sg':
        import rbcc
        from rbcc.backend.runner import SGRunner
        sg = rbcc.load_sg(args.model_file)
        device = f"cuda:{args.device_id}" if args.device_id >= 0 else "cpu"
        runner = SGRunner(sg, device=device, gc_collect=True)
        return WrapRunner(runner, False)
    elif suffix == '.rbo':
        from rboexec.core.client import GRPCClient
        client = GRPCClient(os.environ['CAISA_REMOTE_IP'], int(os.environ['CAISA_REMOTE_PORT']))
        id = client.upload_model(model_path=os.path.abspath(args.model_file), device_id=args.device_id)
        return WrapRunner(client, True, id)
    else:
        raise ValueError(f"excepted .sg or .rbo file, not {suffix}")


def generate_test_dataset(args, transform):
    for person_id, person_name in enumerate(sorted(os.listdir(args.data))):
        person_dir = os.path.join(args.data, person_name)
        for img_name in sorted(os.listdir(person_dir)):
            image_path = os.path.join(person_dir, img_name)
            img = transform(image_path)
            yield img, person_id


def main(args):
    print("INFO: Init Runner.")
    runner = init_runner(args)

    print("INFO: Load dataset.")
    val_loader = generate_test_dataset(args, preprocess)

    # 开始进行评价
    print("INFO: Start inference.")
    pbar = tqdm(desc=f"Eval in Mega-Falce", unit='img', total=160)
    result = []
    labels = []
    for index, (img, person_id) in enumerate(val_loader):
        if index == args.eval_nums:
            break
        pred = runner(img)
        result.append(pred)
        labels.append(person_id)
        pbar.update(1)
    runner.close()
    
    result = np.concatenate(result, 0)
    sim = np.dot(result, result.T) / (np.linalg.norm(result) * np.linalg.norm(result.T))
    mask = (np.eye(*(sim.shape)) != 1.).astype(np.float32)  # exclude themselves
    sim = np.argsort(sim * mask, axis=1)[:, ::-1]
    topk_sim = sim[:, :args.topk]
    
    total, correct = 0, 0
    labels = np.array(labels)
    for query, key in enumerate(topk_sim):
        query_label = labels[query]
        pred_labels = [labels[v] for v in key.tolist()]
        if query_label in pred_labels:
            correct += 1
        total += 1
        
    acc = round((correct / total) * 100, 2)
    print(f"INFO: Acc: {acc}")


if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('model_file', type=str, help='rbo or sg file path.')
    parser.add_argument('--data', type=str, default=None, help='dataset dir.')
    parser.add_argument('--device-id', type=int, default=0, help="device id.")
    parser.add_argument('--eval-nums', type=int, help="The number of data sets that need to be verified.")
    parser.add_argument('--topk', type=int, default=1, help="device id.")
    main(parser.parse_args())
