import os
import argparse

import numpy as np
from tqdm import tqdm

from preprocess import preprocess, postprocess


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, inputs=['image', 'scale_factor'])
        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 img_name in sorted(os.listdir(args.data)):
        img_path = os.path.join(args.data, img_name)
        img, scale_factor = transform(img_path)
        if 'smokers' in img_name:
            label = 0
        elif 'others' in img_name:
            label = 1
        else:
            raise RuntimeError(f'no label in {img_name}')
        yield img, scale_factor, label

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

    print("INFO: Load dataset.")
    val_loader = generate_test_dataset(args, preprocess)
    num_samples = len(os.listdir(args.data)) if not args.eval_nums else args.eval_nums

    # 开始进行评价
    print("INFO: Start inference.")
    pbar = tqdm(desc=f"Eval in Smoking-Data", unit='img', total=num_samples)
    total, correct = 0, 0
    for index, (img, scale_factor, label) in enumerate(val_loader):
        if index == args.eval_nums:
            break
        outputs, det_num = runner(img, scale_factor)
        boxes, scores, labels = postprocess(outputs)
        pred = 0 if scores.max(0) > 0.5 else 1
        if pred == label:
            correct += 1
        total += 1
        pbar.update(1)

    pbar.close()
    runner.close()
    acc = correct / total
    acc = round(acc * 100, 2)
    print(f"INFO: Acc: {acc}", flush=True)


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="device id.")
    main(parser.parse_args())
