import cv2
import numpy as np
import os
import sys
import argparse
import lacinfer

from pathlib import Path

_HELPER_SEARCH_PATH = Path(__file__).resolve()
for _parent in _HELPER_SEARCH_PATH.parents:
    if (_parent / "lacinfer_subprocess_pipeline.py").exists():
        sys.path.insert(0, str(_parent))
        break
from lacinfer_subprocess_pipeline import (
    add_pipeline_args,
    monitor_stage_memory,
    run_split_quant_compile_pipeline,
    run_worker_child,
    should_spawn_worker_child,
    should_split_quant_compile,
    validate_args,
)


class YOLOv5:
    def __init__(self, cocopath, modelpath, obj_thres=0.5, conf_thres=0.25, iou_thres=0.5, offload_copy=True, exhaustive_tune=True):
        self.objectThreshold = obj_thres
        self.confThreshold = conf_thres
        self.nmsThreshold = iou_thres
        # 获取模型检测的类别信息
        self.classNames = list(map(lambda x: x.strip(), open(cocopath, 'r').readlines()))

        # 解析推理模型
        self.model = lacinfer.parse_onnx(modelpath) 
        # 获取模型的输入name
        self.inputName = self.model.get_parameter_names()[0]

        # 获取模型的输入尺寸
        inputShape = self.model.get_parameter_shapes()[self.inputName].lens()
        self.inputHeight = int(inputShape[2])
        self.inputWidth = int(inputShape[3])
        print("inputName:{0} \ninputShape:{1}".format(self.inputName, inputShape))
        
        self.inputType = self.model.get_parameter_shapes()[self.inputName].type_string()
        print("inputType:", self.inputType)

        # 模型编译
        self.model.compile(t=lacinfer.get_target("gpu"), offload_copy=offload_copy, exhaustive_tune=exhaustive_tune)  # device_id: 设置GPU设备，默认为0号设备

    def detect(self, image):
        # 输入图片预处理
        input_img = self.prepare_input(image)

        # 执行推理
        result = self.model.run({self.inputName: input_img})

        # 模型输出结果后处理
        boxes, scores, class_ids = self.process_output(result)

        return boxes, scores, class_ids

    def prepare_input(self, image):
        self.img_height, self.img_width = image.shape[:2]
        input_img = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
        input_img = cv2.resize(input_img, (self.inputWidth, self.inputHeight))
        input_img = input_img.transpose(2, 0, 1)
        input_img = np.expand_dims(input_img, 0)
        input_img = np.ascontiguousarray(input_img)
        if self.inputType == "float_type":
            input_img = input_img.astype(np.float32)
        elif self.inputType == "half_type":
            input_img = input_img.astype(np.float16)
        else:
            raise ValueError(f"Unexpected model inputType: {self.inputType}")
        input_img = input_img / 255

        return input_img

    def process_output(self, output):
        predictions = np.squeeze(output[0])

        # 筛选包含物体的anchor
        obj_conf = predictions[:, 4]
        predictions = predictions[obj_conf > self.objectThreshold]
        obj_conf = obj_conf[obj_conf > self.objectThreshold]

        # 筛选大于置信度阈值的anchor
        predictions[:, 5:] *= obj_conf[:, np.newaxis]
        scores = np.max(predictions[:, 5:], axis=1)
        valid_scores = scores > self.confThreshold
        predictions = predictions[valid_scores]
        scores = scores[valid_scores]

        # 获取最高置信度分数对应的类别ID
        class_ids = np.argmax(predictions[:, 5:], axis=1)

        # 获取每个物体对应的anchor
        boxes = self.extract_boxes(predictions)

        # 执行非极大值抑制消除冗余anchor
        indices = cv2.dnn.NMSBoxes(boxes.tolist(), scores.tolist(), self.confThreshold, self.nmsThreshold).flatten()

        return boxes[indices], scores[indices], class_ids[indices]

    def extract_boxes(self, predictions):
        boxes = predictions[:, :4]
        boxes = self.rescale_boxes(boxes)
        boxes_ = np.copy(boxes)
        boxes_[..., 0] = boxes[..., 0] - boxes[..., 2] * 0.5
        boxes_[..., 1] = boxes[..., 1] - boxes[..., 3] * 0.5
        return boxes_

    def rescale_boxes(self, boxes):
        # 对anchor尺寸进行变换
        input_shape = np.array([self.inputWidth, self.inputHeight, self.inputWidth, self.inputHeight])
        boxes = np.divide(boxes, input_shape, dtype=np.float32)
        boxes *= np.array([self.img_width, self.img_height, self.img_width, self.img_height])
        return boxes

    def draw_detections(self, image, boxes, scores, class_ids):
        for box, score, class_id in zip(boxes, scores, class_ids):
            cx, cy, w, h = box.astype(int)

            # 绘制检测物体框
            cv2.rectangle(image, (cx, cy), (cx + w, cy + h), (0, 255, 255), thickness=2)
            label = self.classNames[class_id]
            label = f'{label} {score:.2f}'
            labelSize, baseLine = cv2.getTextSize(label, cv2.FONT_HERSHEY_SIMPLEX, 0.5, 1)
            cv2.putText(image, label, (cx, cy - 10), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 255), thickness=2)
        return image


def parse_expect(expect_str):
    """Parse --expect argument into (class_name, min_count) list.

    Syntax:
      --expect bus                     -> [('bus', 1)]
      --expect bus,person              -> [('bus', 1), ('person', 1)]
      --expect person:3,bus:1          -> [('person', 3), ('bus', 1)]
    """
    expect_list = []
    for item in expect_str.split(','):
        item = item.strip()
        if ':' in item:
            name, count = item.rsplit(':', 1)
            expect_list.append((name.strip(), int(count)))
        else:
            expect_list.append((item, 1))
    return expect_list


def verify_results(classNames, class_ids, scores, expect_specs, min_confidence=0.5):
    """Verify detection results automatically.

    Args:
        classNames: list of COCO class name strings
        class_ids: array of detected class IDs
        scores: corresponding confidence scores
        expect_specs: list of (class_name, min_count) tuples
        min_confidence: minimum confidence threshold for expected classes

    Returns:
        (passed, details): whether verification passed, detailed message string
    """
    # count detections per class and track max confidence
    detected_count = {}
    detected_max_score = {}
    for cls_id, score in zip(class_ids, scores):
        name = classNames[cls_id]
        detected_count[name] = detected_count.get(name, 0) + 1
        if name not in detected_max_score or score > detected_max_score[name]:
            detected_max_score[name] = score

    details_lines = []
    details_lines.append("=" * 50)
    details_lines.append("Detection Result Verification")
    details_lines.append("=" * 50)
    details_lines.append(f"Total {len(class_ids)} objects detected:")
    for cls_id, score in sorted(zip(class_ids, scores), key=lambda x: -x[1]):
        details_lines.append(f"  - {classNames[cls_id]:20s} confidence: {score:.4f}")

    details_lines.append("")
    all_pass = True
    for expect_class, expect_count in expect_specs:
        actual_count = detected_count.get(expect_class, 0)
        max_score = detected_max_score.get(expect_class, 0.0)
        if actual_count >= expect_count and max_score >= min_confidence:
            details_lines.append(
                f"  ✓ expected '{expect_class}' "
                f"(count {actual_count} >= {expect_count}, max confidence {max_score:.4f} >= {min_confidence})")
        elif actual_count >= expect_count and max_score < min_confidence:
            details_lines.append(
                f"  ⚠ expected '{expect_class}' count OK ({actual_count} >= {expect_count}) "
                f"but confidence too low ({max_score:.4f} < {min_confidence})")
            all_pass = False
        elif actual_count < expect_count and max_score >= min_confidence:
            details_lines.append(
                f"  ⚠ expected '{expect_class}' confidence OK ({max_score:.4f} >= {min_confidence}) "
                f"but count insufficient ({actual_count} < {expect_count})")
            all_pass = False
        else:
            details_lines.append(
                f"  ✗ expected '{expect_class}' not satisfied "
                f"(count {actual_count} < {expect_count}, max confidence {max_score:.4f} < {min_confidence})")
            all_pass = False

    details_lines.append("")
    if all_pass:
        details_lines.append(">>>  verdict: PASS  <<<")
    else:
        details_lines.append(">>>  verdict: FAIL  <<<")
    details_lines.append("=" * 50)

    return all_pass, "\n".join(details_lines)


def yolov5_Static(imgpath, cocopath, modelpath, objectThreshold, confThreshold, nmsThreshold, respath,
                  expect_specs=None, min_confidence=0.5, offload_copy=True, exhaustive_tune=True):
    yolov5_detector = YOLOv5(cocopath, modelpath, obj_thres=objectThreshold, conf_thres=confThreshold,
                             iou_thres=nmsThreshold, offload_copy=offload_copy, exhaustive_tune=exhaustive_tune)
    srcimg = cv2.imread(imgpath, 1)

    boxes, scores, class_ids = yolov5_detector.detect(srcimg)

    if expect_specs:
        passed, verdict = verify_results(yolov5_detector.classNames, class_ids, scores,
                                          expect_specs, min_confidence)
        print(verdict)
    else:
        passed = True

    dstimg = yolov5_detector.draw_detections(srcimg, boxes, scores, class_ids)

    # save result image
    cv2.imwrite(respath, dstimg)
    print("Success to save result: ", respath)

    return passed


if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--imgPath', type=str, default='../images/bus.jpg', help="image path")
    parser.add_argument('--cocoClassPath', type=str, default='../models/coco.names', help="coco classes path")
    parser.add_argument('--staticModelPath', type=str, default='../models/f32_model/yolov5s_float32.onnx', help="static onnx filepath")
    parser.add_argument('--objectThreshold', default=0.5, type=float, help='class confidence')
    parser.add_argument('--confThreshold', default=0.25, type=float, help='class confidence')
    parser.add_argument('--nmsThreshold', default=0.5, type=float, help='nms iou thresh')
    parser.add_argument('--resPath', type=str, default='./Result.jpg', help="result path")
    parser.add_argument('--expect', type=str, default=None,
                        help='expected class:count, comma-separated (e.g. --expect bus,person:3)')
    parser.add_argument('--minConfidence', type=float, default=0.5,
                        help='minimum confidence threshold for expected classes')
    parser.add_argument('--no-offload-copy', action='store_false', dest='offload_copy',
                        help='Disable offload copy during compilation')
    parser.add_argument('--no-exhaustive-tune', action='store_false', dest='exhaustive_tune', default=True, help='Disable exhaustive tuning during compilation')
    add_pipeline_args(parser)
    args = parser.parse_args()
    monitor_stage_memory(args)

    arg_names = [
        "imgPath", "cocoClassPath", "staticModelPath", "objectThreshold", "confThreshold",
        "nmsThreshold", "resPath", "minConfidence",
    ]
    optional_arg_names = ["expect"]
    flag_specs = [("offload_copy", "--no-offload-copy", False), ("exhaustive_tune", "--no-exhaustive-tune", False)]
    script_path = os.path.abspath(__file__)

    if should_spawn_worker_child(args):
        run_worker_child(args, script_path, arg_names, optional_arg_names, flag_specs)
        sys.exit(0)

    expect_specs = parse_expect(args.expect) if args.expect else None
    if expect_specs:
        print("expect specs:", expect_specs)
    passed = yolov5_Static(args.imgPath, args.cocoClassPath, args.staticModelPath,
                  args.objectThreshold, args.confThreshold, args.nmsThreshold,
                  args.resPath, expect_specs, args.minConfidence,
                  offload_copy=args.offload_copy, exhaustive_tune=args.exhaustive_tune)
    sys.exit(0 if passed else 1)
