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


class YOLO26:
    def __init__(self, cocopath, modelpath, calpath, action, modelformat, quantonly, savelirs,
                 obj_thres=0.25, iou_thres=0.45, per_channel_ops=None):
        self.objectThreshold = obj_thres
        self.nmsThreshold = iou_thres
        self.classNames = list(map(lambda x: x.strip(), open(cocopath, 'r').readlines()))
        self.input_size = (640, 640)

        if modelformat == "onnx":
            self.model = lacinfer.parse_onnx(modelpath)
        elif modelformat == "lir" or modelformat == "lir-compiled":
            self.model = lacinfer.load(modelpath, format="msgpack")
        else:
            raise ValueError(f"Unexpected model format: {modelformat}")

        self.inputName = self.model.get_parameter_names()[0]
        inputShape = self.model.get_parameter_shapes()[self.inputName]
        inputLens = inputShape.lens()
        inputType = str(inputShape.type_string()) if hasattr(inputShape, 'type_string') else 'float_type'
        self.inputHeight = int(inputLens[2])
        self.inputWidth = int(inputLens[3])
        print("inputName:{0} \ninputShape:{1}".format(self.inputName, inputLens))

        # 检测输入类型：int8 模型用 (pixel - 128)，float 模型用 (pixel / 255.0)
        self.isInt8Input = 'int8' in inputType.lower()
        print("input type:", inputType, "-> using int8 quantization" if self.isInt8Input else "-> using float32 normalization")

        if action == "quant-int8" or action == "quant-fp16":
            if action == "quant-fp16":
                print("quantizing to fp16...")
                lacinfer.quantize_fp16(self.model)
            else:
                print("quantizing to int8...")
                if per_channel_ops:
                    print("using per-channel quantization:", per_channel_ops)
                print("using calibration:", calpath)
                caldata = []
                images = []
                image_files = [f for f in os.listdir(calpath) if f.endswith(('.png', '.jpg', '.jpeg'))]
                for image_file in image_files:
                    calname = os.path.join(calpath, image_file)
                    srcimg = cv2.imread(calname, 1)
                    input_img = self.prepare_input(srcimg)
                    images.append(input_img)
                caldata = [{self.inputName: lacinfer.argument(img)} for img in images]
                print("calibration num:", len(caldata))
                lacinfer.quantize_int8(self.model, lacinfer.get_target("gpu"), caldata,
                                       per_channel_ops=(per_channel_ops or set()))
        elif action != "infer":
            raise ValueError(f"Unexpected action: {action}")

        model_base = os.path.splitext(os.path.basename(modelpath))[0]

        if quantonly or savelirs:
            if modelformat != "lir-compiled":
                print("saving lir:", f"{model_base}-{action}.lir")
                lacinfer.save(self.model, f"{model_base}-{action}.lir")

        if modelformat != "lir-compiled" and not quantonly:
            print("compiling...")
            self.model.compile(t=lacinfer.get_target("gpu"))
            if savelirs:
                print("saving lir:", f"{model_base}-{action}-compiled.lir")
                lacinfer.save(self.model, f"{model_base}-{action}-compiled.lir")

    def nms(self, detections):
        if not detections:
            return [], [], []

        detections = sorted(detections, key=lambda x: x[4], reverse=True)

        boxes, scores, class_ids = [], [], []

        while detections:
            best = detections.pop(0)
            boxes.append([best[0], best[1], best[2], best[3]])
            scores.append(best[4])
            class_ids.append(best[5])

            to_remove = []
            for i, det in enumerate(detections):
                iou = self.compute_iou(best[:4], det[:4])
                if iou > self.nmsThreshold:
                    to_remove.append(i)

            for idx in reversed(to_remove):
                detections.pop(idx)

        return np.array(boxes), np.array(scores), np.array(class_ids)


    def compute_iou(self, box1, box2):
        x1_1, y1_1, x2_1, y2_1 = box1
        x1_2, y1_2, x2_2, y2_2 = box2

        inter_x1 = max(x1_1, x1_2)
        inter_y1 = max(y1_1, y1_2)
        inter_x2 = min(x2_1, x2_2)
        inter_y2 = min(y2_1, y2_2)

        if inter_x2 <= inter_x1 or inter_y2 <= inter_y1:
            return 0.0

        inter_area = (inter_x2 - inter_x1) * (inter_y2 - inter_y1)
        area1 = (x2_1 - x1_1) * (y2_1 - y1_1)
        area2 = (x2_2 - x1_2) * (y2_2 - y1_2)
        union_area = area1 + area2 - inter_area

        return inter_area / union_area if union_area > 0 else 0.0

    def decode_dfl_box(self, box_data, i, j, reg_max):
        l = 0.0
        t = 0.0
        r = 0.0
        b = 0.0
        for k in range(reg_max):
            l += k * box_data[0, k, i, j]
            t += k * box_data[0, reg_max + k, i, j]
            r += k * box_data[0, 2 * reg_max + k, i, j]
            b += k * box_data[0, 3 * reg_max + k, i, j]
        return l, t, r, b

    def detect(self, image):
        input_img = self.prepare_input(image)

        print("running...")
        result = self.model.run({self.inputName: input_img})

        boxes, scores, class_ids = self.process_output(result)

        if boxes is not None:
            boxes[:, [0, 2]] -= self.pad_left
            boxes[:, [1, 3]] -= self.pad_top
            boxes[:, [0, 2]] /= self.scale_ratio
            boxes[:, [1, 3]] /= self.scale_ratio
            boxes[:, [0, 2]] = np.clip(boxes[:, [0, 2]], 0, self.img_width)
            boxes[:, [1, 3]] = np.clip(boxes[:, [1, 3]], 0, self.img_height)

        return boxes, scores, class_ids

    def prepare_input(self, image):
        self.img_height, self.img_width = image.shape[:2]
        self.scale_ratio = min(self.inputWidth / self.img_width, self.inputHeight / self.img_height)
        new_w = int(self.img_width * self.scale_ratio)
        new_h = int(self.img_height * self.scale_ratio)
        resized = cv2.resize(image, (new_w, new_h), interpolation=cv2.INTER_LINEAR)
        canvas = np.full((self.inputHeight, self.inputWidth, 3), 114, dtype=np.uint8)
        self.pad_top = (self.inputHeight - new_h) // 2
        self.pad_left = (self.inputWidth - new_w) // 2
        canvas[self.pad_top:self.pad_top+new_h, self.pad_left:self.pad_left+new_w] = resized
        input_img = cv2.cvtColor(canvas, cv2.COLOR_BGR2RGB)
        input_img = input_img.transpose(2, 0, 1)
        input_img = np.expand_dims(input_img, 0)
        input_img = np.ascontiguousarray(input_img)

        # 根据模型输入类型选择预处理方式
        if self.isInt8Input:
            # int8 量化：pixel - 128（参考 yolo26/src/detector.cpp 第 113-115 行）
            input_img = (input_img.astype(np.int32) - 128).astype(np.int8)
        else:
            # float32 归一化：pixel / 255.0
            input_img = input_img.astype(np.float32) / 255.0

        return input_img

    def process_output(self, outputs):
        outputs = [np.array(out) for out in outputs]

        strides = [8, 16, 32]
        all_detections = []
        input_width, input_height = self.input_size  # (640, 640)

        for level in range(3):
            idx_base = level * 3

            box_data = outputs[idx_base]      # [1, 4, h, w] 或 [1, 64, h, w]
            cls_data = outputs[idx_base + 1]  # [1, num_classes, h, w]
            obj_data = outputs[idx_base + 2]  # [1, 1, h, w]

            box_shape = box_data.shape
            if len(box_shape) != 4:
                continue

            h, w = box_shape[2], box_shape[3]
            box_channels = box_shape[1]
            cls_channels = cls_data.shape[1]

            stride = input_width // w
            use_dfl = (box_channels > 4)  # YOLO26s: False

            for i in range(h):
                for j in range(w):
                    idx = i * w + j

                    obj_conf = obj_data[0, 0, i, j]
                    if obj_conf < self.objectThreshold:
                        continue

                    max_prob = 0.0
                    max_class = 0
                    for c in range(cls_channels):
                        prob = cls_data[0, c, i, j]
                        if prob > max_prob:
                            max_prob = prob
                            max_class = c

                    if max_prob < self.objectThreshold:
                        continue

                    if use_dfl:
                        l, t, r, b = self.decode_dfl_box(box_data, i, j, box_channels // 4)
                        x1 = (j + 0.5 - l) * stride
                        y1 = (i + 0.5 - t) * stride
                        x2 = (j + 0.5 + r) * stride
                        y2 = (i + 0.5 + b) * stride
                    else:
                        dx1 = box_data[0, 0, i, j]
                        dy1 = box_data[0, 1, i, j]
                        dx2 = box_data[0, 2, i, j]
                        dy2 = box_data[0, 3, i, j]

                        x1 = (j + 0.5 - dx1) * stride
                        y1 = (i + 0.5 - dy1) * stride
                        x2 = (j + 0.5 + dx2) * stride
                        y2 = (i + 0.5 + dy2) * stride

                    box_width = x2 - x1
                    box_height = y2 - y1

                    if box_width <= 0 or box_height <= 0:
                        continue

                    if x1 < -50 or y1 < -50 or x2 > input_width + 50 or y2 > input_height + 50:
                        continue

                    all_detections.append([x1, y1, x2, y2, max_prob, max_class])

        if len(all_detections) == 0:
            return None, None, None

        boxes, confidences, class_ids = self.nms(all_detections)

        return boxes, confidences, class_ids

    def draw_detections(self, image, boxes, scores, class_ids):
        for box, score, cl in zip(boxes, scores, class_ids):
            x1, y1, x2, y2 = [int(_b) for _b in box]
            cl = int(cl)
            label = self.classNames[cl] if cl < len(self.classNames) else str(cl)
            cv2.rectangle(image, (x1, y1), (x2, y2), (255, 0, 0), 2)
            cv2.putText(image, '{0} {1:.2f}'.format(label, score),
                        (x1, y1 - 6), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 0, 255), 2)


def main_func(imgpath, cocopath, modelpath, calpath, action, modelformat, quantonly,
              savelirs, objectThreshold, nmsThreshold, respath, per_channel_ops=None):
    detector = YOLO26(cocopath, modelpath, calpath, action, modelformat, quantonly,
                      savelirs, obj_thres=objectThreshold, iou_thres=nmsThreshold,
                      per_channel_ops=per_channel_ops)

    if not quantonly:
        srcimg = cv2.imread(imgpath, 1)
        boxes, scores, class_ids = detector.detect(srcimg)

        if boxes is not None:
            dstimg = srcimg.copy()
            detector.draw_detections(dstimg, boxes, scores, class_ids)
            cv2.imwrite(respath, dstimg)
            print("Success to save result", respath)
        else:
            print("Nothing detected!")


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/yolo26s.onnx', help="static onnx filepath")
    parser.add_argument('--objectThreshold', default=0.25, type=float, help='class confidence')
    parser.add_argument('--nmsThreshold', default=0.45, type=float, help='nms iou thresh')
    parser.add_argument('--resPath', type=str, default='./Result.jpg', help="result path")
    parser.add_argument('--calibrationPath', type=str, default='../images', help="calibration path for quantization")
    parser.add_argument('--action', type=str, default='infer', help="action: infer, quant-int8 or quant-fp16")
    parser.add_argument('--modelFormat', type=str, default='onnx', help="model format: onnx, lir or lir-compiled")
    parser.add_argument("--quantOnly", action="store_true", default=False, help="only quantize the model")
    parser.add_argument("--saveLirs", action="store_true", default=False, help="save quantized and compiled lir models")
    parser.add_argument("--per-channel", action="store_true", default=False,
                        help="use per-channel quantization for convolution weights")
    args = parser.parse_args()

    if args.modelFormat == "lir-compiled" and args.action != "infer":
        raise ValueError(f"Compiled lir model can only infer directly")
    if args.quantOnly and args.action == "infer":
        raise ValueError(f"Quant action must be set for quantizing")

    print("image:", args.imgPath)
    print("model:", args.staticModelPath)
    print("objconf threshold:", args.objectThreshold)
    print("nms threshold:", args.nmsThreshold)
    if args.quantOnly:
        print("quant only!")

    main_func(args.imgPath, args.cocoClassPath, args.staticModelPath, args.calibrationPath, args.action,
              args.modelFormat, args.quantOnly, args.saveLirs, args.objectThreshold, args.nmsThreshold, args.resPath,
              per_channel_ops={"convolution"} if args.per_channel else set())
