import cv2
import numpy as np
import os
import argparse
import gc
import sys
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_split_compile_infer_pipeline,
    run_worker_child,
    should_spawn_worker_child,
    should_split_compile_infer,
    should_split_quant_compile,
    validate_args,
)


def sigmoid(x):
    return 1 / (1 + np.exp(-x))


def nms_boxes(boxes, scores, nms_thresh):
    x1 = boxes[:, 0]
    y1 = boxes[:, 1]
    x2 = boxes[:, 2]
    y2 = boxes[:, 3]

    areas = (x2 - x1) * (y2 - y1)
    order = scores.argsort()[::-1]

    keep = []
    while order.size > 0:
        i = order[0]
        keep.append(i)

        xx1 = np.maximum(x1[i], x1[order[1:]])
        yy1 = np.maximum(y1[i], y1[order[1:]])
        xx2 = np.minimum(x2[i], x2[order[1:]])
        yy2 = np.minimum(y2[i], y2[order[1:]])

        w = np.maximum(0.0, xx2 - xx1 + 1e-5)
        h = np.maximum(0.0, yy2 - yy1 + 1e-5)
        inter = w * h

        union = areas[i] + areas[order[1:]] - inter
        iou = inter / np.maximum(union, 1e-12)

        inds = np.where(iou <= nms_thresh)[0]
        order = order[inds + 1]

    return np.array(keep, dtype=np.int64)


class YOLOv9:
    def __init__(self, cocopath, modelpath, calpath, action, modelformat, quantonly, savelirs,
                 obj_thres=0.25, iou_thres=0.45, per_channel_ops=None,
                 asymmetric_activation_ops=None,
                 output_prefix=None, save_uncompiled_lir=True, save_compiled_lir=True, offload_copy=True, skip_infer=False, exhaustive_tune=True):
        self.objectThreshold = obj_thres
        self.nmsThreshold = iou_thres
        self.classNames = list(map(lambda x: x.strip(), open(cocopath, 'r').readlines()))

        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].lens()
        self.inputHeight = int(inputShape[2])
        self.inputWidth = int(inputShape[3])
        print("inputName:{0} \ninputShape:{1}".format(self.inputName, inputShape))

        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)
                if asymmetric_activation_ops:
                    print("using asymmetric activation quantization:", asymmetric_activation_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,
                                       asymmetric_activation_ops=(asymmetric_activation_ops or set()),
                                       per_channel_ops=(per_channel_ops or set()))
                del caldata
                del images
                gc.collect()
        elif action != "infer":
            raise ValueError(f"Unexpected action: {action}")

        model_base = os.path.splitext(os.path.basename(modelpath))[0]
        save_prefix = output_prefix or f"{model_base}-{action}"

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

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

    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)
        input_img = input_img.astype(np.float32)
        input_img = input_img / 255.0

        return input_img

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

        if hasattr(self, 'debug') and self.debug:
            print("\n=== process_output Debug ===")
            print(f"Number of outputs: {len(outputs)}")
            for i, out in enumerate(outputs):
                print(f"  Output {i}: shape={out.shape}")

        strides = [8, 16, 32]
        reg_max = 16  # 4*16=64
        nc = 80

        all_boxes = []
        all_scores = []
        all_classes = []

        img_width = 640
        img_height = 640

        for s in range(3):
            box_out = outputs[s * 3]      # (1, 64, H, W)
            score_out = outputs[s * 3 + 1]  # (1, 80, H, W)
            sum_out = outputs[s * 3 + 2]   # (1, 1, H, W)

            _, _, h, w = box_out.shape
            stride = strides[s]

            if hasattr(self, 'debug') and self.debug:
                print(f"\n尺度 {s}: {h}x{w}, stride={stride}")

            box_data = box_out.squeeze(0)  # (64, H, W)
            score_data = score_out.squeeze(0)  # (80, H, W)
            sum_data = sigmoid(sum_out.squeeze(0))  # (H, W)

            anchor_x = np.zeros((h, w))
            anchor_y = np.zeros((h, w))
            for i in range(h):
                for j in range(w):
                    anchor_x[i, j] = (j + 0.5) * stride
                    anchor_y[i, j] = (i + 0.5) * stride

            anchor_x_flat = anchor_x.flatten()  # (H*W,)
            anchor_y_flat = anchor_y.flatten()  # (H*W,)
            sum_flat = sum_data.flatten()  # (H*W,)

            for idx in range(h * w):
                if sum_flat[idx] < 0.05:
                    continue

                max_score = 0.0
                best_cls = 0
                for c in range(nc):
                    prob = score_data[c, idx // w, idx % w]
                    if prob > max_score:
                        max_score = prob
                        best_cls = c

                if max_score < self.objectThreshold:
                    continue

                dists = np.zeros(4)
                for k in range(4):
                    dptr = box_data[k * reg_max:(k + 1) * reg_max, :, :]  # (16, H, W)
                    dptr_idx = dptr[:, idx // w, idx % w]  # (16,)

                    # Softmax
                    max_val = np.max(dptr_idx)
                    exp_vals = np.exp(dptr_idx - max_val)
                    sum_exp = np.sum(exp_vals)

                    weighted = 0.0
                    for d in range(reg_max):
                        weighted += exp_vals[d] * d

                    dists[k] = (weighted / sum_exp) * stride

                x1 = anchor_x_flat[idx] - dists[0]
                y1 = anchor_y_flat[idx] - dists[1]
                x2 = anchor_x_flat[idx] + dists[2]
                y2 = anchor_y_flat[idx] + dists[3]

                if x1 >= x2 or y1 >= y2:
                    continue

                x1 = max(0, min(x1, img_width))
                y1 = max(0, min(y1, img_height))
                x2 = max(0, min(x2, img_width))
                y2 = max(0, min(y2, img_height))

                if x2 > x1 and y2 > y1:
                    all_boxes.append([x1, y1, x2, y2])
                    all_scores.append(max_score)
                    all_classes.append(best_cls)

        if hasattr(self, 'debug') and self.debug:
            print(f"\nTotal detections before NMS: {len(all_boxes)}")

        if not all_boxes:
            if hasattr(self, 'debug') and self.debug:
                print("No detections found!")
            return None, None, None

        boxes = np.array(all_boxes)
        scores = np.array(all_scores)
        classes = np.array(all_classes)

        sort_idx = np.argsort(scores)[::-1]
        boxes = boxes[sort_idx]
        scores = scores[sort_idx]
        classes = classes[sort_idx]

        keep_indices = []
        for i in range(len(boxes)):
            if scores[i] < 0:
                continue
            keep_indices.append(i)
            for j in range(i + 1, len(boxes)):
                if scores[j] < 0:
                    continue
                box1 = boxes[i]
                box2 = boxes[j]

                inter_x1 = max(box1[0], box2[0])
                inter_y1 = max(box1[1], box2[1])
                inter_x2 = min(box1[2], box2[2])
                inter_y2 = min(box1[3], box2[3])

                if inter_x2 > inter_x1 and inter_y2 > inter_y1:
                    inter_area = (inter_x2 - inter_x1) * (inter_y2 - inter_y1)
                    box1_area = (box1[2] - box1[0]) * (box1[3] - box1[1])
                    box2_area = (box2[2] - box2[0]) * (box2[3] - box2[1])
                    union_area = box1_area + box2_area - inter_area
                    iou = inter_area / union_area if union_area > 0 else 0

                    if iou > self.nmsThreshold:
                        scores[j] = -1

        if not keep_indices:
            if hasattr(self, 'debug') and self.debug:
                print("No detections after NMS!")
            return None, None, None

        boxes = boxes[keep_indices]
        scores = scores[keep_indices]
        classes = classes[keep_indices]

        if hasattr(self, 'debug') and self.debug:
            print(f"Detections after NMS: {len(boxes)}")
            for i in range(len(boxes)):
                print(f"  {i}: class={classes[i]}, score={scores[i]:.4f}, "
                      f"bbox=({boxes[i][0]:.1f}, {boxes[i][1]:.1f}, "
                      f"{boxes[i][2]:.1f}, {boxes[i][3]:.1f})")

        return boxes, scores, classes

    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]
            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,
                 asymmetric_activation_ops=None,
                 output_prefix=None, save_uncompiled_lir=True, save_compiled_lir=True, skip_infer=False, offload_copy=True, exhaustive_tune=True):
    detector = YOLOv9(cocopath, modelpath, calpath, action, modelformat, quantonly,
                      savelirs, obj_thres=objectThreshold, iou_thres=nmsThreshold,
                      per_channel_ops=per_channel_ops,
                      asymmetric_activation_ops=asymmetric_activation_ops,
                      output_prefix=output_prefix,
                      save_uncompiled_lir=save_uncompiled_lir,
                      save_compiled_lir=save_compiled_lir,
                      offload_copy=offload_copy,
                      exhaustive_tune=exhaustive_tune)

    if not quantonly and not skip_infer:
        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/yolov9s.onnx', help="static onnx filepath")
    parser.add_argument('--objectThreshold', default=0.7, 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")
    parser.add_argument("--asymmetric-activation", action="store_true", default=False,
                        help="use asymmetric activation quantization for convolution ops")
    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)

    validate_args(args)

    arg_names = [
        "imgPath", "cocoClassPath", "staticModelPath", "objectThreshold", "nmsThreshold",
        "resPath", "calibrationPath", "action", "modelFormat",
    ]
    flag_specs = ["quantOnly", "saveLirs", ("per_channel", "--per-channel"),
                  ("asymmetric_activation", "--asymmetric-activation"),
                  ("offload_copy", "--no-offload-copy", False), ("exhaustive_tune", "--no-exhaustive-tune", False)]
    script_path = os.path.abspath(__file__)

    if should_split_quant_compile(args):
        run_split_quant_compile_pipeline(args, script_path, arg_names, flag_specs=flag_specs,
                                         include_model_base=True)
        sys.exit(0)
    if should_split_compile_infer(args):
        run_split_compile_infer_pipeline(args, script_path, arg_names, flag_specs=flag_specs,
                                         include_model_base=True)
        sys.exit(0)
    if should_spawn_worker_child(args):
        run_worker_child(args, script_path, arg_names, flag_specs=flag_specs)
        sys.exit(0)

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

    stage = args.pipelineStage
    quantonly = True if stage == "quant-save" else args.quantOnly
    savelirs = True if stage in ("quant-save", "compile-save") else args.saveLirs
    action = "infer" if stage == "compile-save" else args.action
    skip_infer = stage in ("quant-save", "compile-save") or not args.offload_copy
    main_func(args.imgPath, args.cocoClassPath, args.staticModelPath, args.calibrationPath, action,
              args.modelFormat, quantonly, savelirs, args.objectThreshold, args.nmsThreshold, args.resPath,
              per_channel_ops={"convolution"} if getattr(args, "per_channel", False) else set(),
              asymmetric_activation_ops={"convolution"} if args.asymmetric_activation else set(),
              output_prefix=args.outputPrefix,
              save_uncompiled_lir=stage != "compile-save",
              save_compiled_lir=stage != "quant-save",
              skip_infer=skip_infer,
              offload_copy=args.offload_copy,
              exhaustive_tune=args.exhaustive_tune)
