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,
)


MAX_DETECT = 300


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


def softmax(x, axis):
    x_max = np.amax(x, axis=axis, keepdims=True)
    e_x = np.exp(x - x_max)
    return e_x / np.sum(e_x, axis=axis, keepdims=True)


def dfl(position):
    n, c, h, w = position.shape
    p_num = 4
    mc = c // p_num
    y = position.reshape(n, p_num, mc, h, w)
    y = softmax(y, axis=2)
    acc = np.arange(mc, dtype=np.float32).reshape(1, 1, mc, 1, 1)
    y = (y * acc).sum(axis=2)
    return y


def box_process(position, input_size):
    input_w, input_h = input_size
    grid_h, grid_w = position.shape[2:4]
    col, row = np.meshgrid(np.arange(0, grid_w), np.arange(0, grid_h))
    col = col.reshape(1, 1, grid_h, grid_w)
    row = row.reshape(1, 1, grid_h, grid_w)
    grid = np.concatenate((col, row), axis=1)

    stride = np.array([input_w / grid_w, input_h / grid_h], dtype=np.float32).reshape(1, 2, 1, 1)

    position = dfl(position)
    box_xy = grid + 0.5 - position[:, 0:2, :, :]
    box_xy2 = grid + 0.5 + position[:, 2:4, :, :]
    xyxy = np.concatenate((box_xy * stride, box_xy2 * stride), axis=1)

    return xyxy


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)


def crop_mask(masks, boxes):
    n, h, w = masks.shape
    x1, y1, x2, y2 = np.split(boxes[:, :, None], 4, axis=1)
    r = np.arange(w, dtype=boxes.dtype)[None, None, :]
    c = np.arange(h, dtype=boxes.dtype)[None, :, None]
    return masks * ((r >= x1) * (r < x2) * (c >= y1) * (c < y2))


class Colors:
    def __init__(self):
        hexs = ('FF3838', 'FF9D97', 'FF701F', 'FFB21D', 'CFD231', '48F90A', '92CC17', '3DDB86', '1A9334', '00D4BB',
                '2C99A8', '00C2FF', '344593', '6473FF', '0018EC', '8438FF', '520085', 'CB38FF', 'FF95C8', 'FF37C7')
        self.palette = [self.hex2rgb(f'#{c}') for c in hexs]
        self.n = len(self.palette)

    def __call__(self, i, bgr=False):
        c = self.palette[int(i) % self.n]
        return (c[2], c[1], c[0]) if bgr else c

    @staticmethod
    def hex2rgb(h):
        return tuple(int(h[1 + i:1 + i + 2], 16) for i in (0, 2, 4))


class YOLOv8Seg:
    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, seg_img = 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)

            if seg_img is not None:
                seg_img = self.get_real_seg(seg_img)

        return boxes, scores, class_ids, seg_img

    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]
        input_size = (self.inputWidth, self.inputHeight)

        # Last output is proto
        proto = outputs[-1]
        num_outputs = len(outputs) - 1  # exclude proto
        default_branch = 3
        pair_per_branch = num_outputs // default_branch

        boxes_list, scores_list, seg_list = [], [], []

        for i in range(default_branch):
            box_out = outputs[pair_per_branch * i]
            cls_out = outputs[pair_per_branch * i + 1]

            # seg is either the 3rd or 4th output per branch
            if pair_per_branch >= 4:
                seg_out = outputs[pair_per_branch * i + 3]
            else:
                seg_out = outputs[pair_per_branch * i + 2]

            boxes_list.append(box_process(box_out, input_size))

            num_classes = cls_out.shape[1]
            scores_flat = cls_out.transpose(0, 2, 3, 1).reshape(-1, num_classes)
            scores_list.append(scores_flat)

            def sp_flatten(_in):
                ch = _in.shape[1]
                _in = _in.transpose(0, 2, 3, 1)
                return _in.reshape(-1, ch)

            seg_list.append(sp_flatten(seg_out))

        def flatten_boxes(b):
            return b.transpose(0, 2, 3, 1).reshape(-1, 4)

        boxes = np.concatenate([flatten_boxes(v) for v in boxes_list])
        scores_all = np.concatenate(scores_list)
        seg_part = np.concatenate(seg_list)

        classes = scores_all.argmax(axis=1)
        max_scores = scores_all.max(axis=1)

        keep_mask = max_scores >= self.objectThreshold
        boxes = boxes[keep_mask]
        classes = classes[keep_mask]
        max_scores = max_scores[keep_mask]
        seg_part = seg_part[keep_mask]

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

        # Sort by score
        sort_idx = np.argsort(max_scores)[::-1]
        max_nms = 30000
        if len(sort_idx) > max_nms:
            sort_idx = sort_idx[:max_nms]
        boxes = boxes[sort_idx]
        classes = classes[sort_idx]
        max_scores = max_scores[sort_idx]
        seg_part = seg_part[sort_idx]

        # Per-class NMS with agnostic offset
        max_wh = 7680
        c = classes.astype(np.float32) * max_wh
        offset_boxes = boxes + c[:, None]
        keep = nms_boxes(offset_boxes, max_scores, self.nmsThreshold)
        if len(keep) > MAX_DETECT:
            keep = keep[:MAX_DETECT]

        boxes = boxes[keep]
        classes = classes[keep]
        max_scores = max_scores[keep]
        seg_part = seg_part[keep]

        # Generate segmentation masks
        ph, pw = proto.shape[-2:]
        proto_reshaped = proto.reshape(seg_part.shape[-1], -1)
        seg_img = np.matmul(seg_part, proto_reshaped)
        seg_img = sigmoid(seg_img)
        seg_img = seg_img.reshape(-1, ph, pw)

        seg_threshold = 0.5

        # Resize seg to input size
        seg_img_resized = []
        for i in range(seg_img.shape[0]):
            seg = cv2.resize(seg_img[i], (self.inputWidth, self.inputHeight), interpolation=cv2.INTER_LINEAR)
            seg_img_resized.append(seg)
        seg_img = np.array(seg_img_resized)

        seg_img = crop_mask(seg_img, boxes)
        seg_img = seg_img > seg_threshold

        return boxes, max_scores, classes, seg_img

    def get_real_seg(self, seg_img):
        # Use int() (truncation) to match prepare_input's new_w/new_h calculation
        content_w = int(self.img_width * self.scale_ratio)
        content_h = int(self.img_height * self.scale_ratio)

        real_segs = []
        for i in range(seg_img.shape[0]):
            mask = seg_img[i].astype(np.float32)
            mask = mask[self.pad_top:self.pad_top + content_h, self.pad_left:self.pad_left + content_w]
            mask = cv2.resize(mask, (self.img_width, self.img_height), interpolation=cv2.INTER_LINEAR)
            mask = (mask > 0.5).astype(np.uint8)
            real_segs.append(mask)

        return np.array(real_segs)

    def merge_seg(self, image, seg_img, classes):
        color = Colors()
        for i in range(len(seg_img)):
            mask = seg_img[i]  # binary mask (bool or uint8)
            if mask.dtype != np.uint8:
                mask = mask.astype(np.uint8) * 255
            # Create color layer (BGR)
            color_bgr = color(int(classes[i]), bgr=True)
            color_layer = np.full(image.shape, color_bgr, dtype=np.uint8)
            # Alpha blend: 0.4 mask color + 1.0 original (matching C++ utils.cpp)
            blended = cv2.addWeighted(color_layer, 0.4, image, 1.0, 0.0)
            # Apply only where mask is foreground
            mask_3ch = cv2.cvtColor(mask, cv2.COLOR_GRAY2BGR)
            np.copyto(image, blended, where=mask_3ch > 0)
        return image

    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)
            # Box color matching C++ utils.cpp: BGR(229, 160, 21)
            cv2.rectangle(image, (x1, y1), (x2, y2), (229, 160, 21), 2)
            # Label background
            (tw, th), _ = cv2.getTextSize(label, cv2.FONT_HERSHEY_SIMPLEX, 0.8, 2)
            cv2.rectangle(image, (x1, y1 - th - 6), (x1 + tw, y1), (229, 160, 21), -1)
            cv2.putText(image, label,
                        (x1, y1 - 6), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (255, 255, 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 = YOLOv8Seg(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, seg_img = detector.detect(srcimg)

        if boxes is not None:
            dstimg = srcimg.copy()
            if seg_img is not None:
                dstimg = detector.merge_seg(dstimg, seg_img, class_ids)
            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/yolov8s-seg.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")
    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)
