import cv2
import numpy as np
import os
import math
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,
)


# DOTA 15 classes for OBB
CLASSES = ("plane", "ship", "storage tank", "baseball diamond", "tennis court",
           "basketball court", "ground track field", "harbor", "bridge",
           "large vehicle", "small vehicle", "helicopter", "roundabout",
           "soccer ball field", "swimming pool")

NUM_CLASSES = 15
DFL_CHANNELS = 64  # 4 * reg_max(16)


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 sigmoid(x):
    return 1 / (1 + np.exp(-x))


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


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 YOLOv8OBB:
    def __init__(self, modelpath, calpath, action, modelformat, quantonly, savelirs,
                 force_i8_output=False, obj_thres=0.45, iou_thres=0.1, 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):
        self.objectThreshold = obj_thres
        self.nmsThreshold = iou_thres
        self.output_scales = None

        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))
                if force_i8_output:
                    print("force int8 output enabled")
                lacinfer.quantize_int8(self.model, lacinfer.get_target("gpu"), caldata,
                                       force_i8_output=force_i8_output,
                                       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}")

        self._collect_output_scales()

        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 _collect_output_scales(self):
        self.output_scales = None
        try:
            mm = self.model.get_main_module()
        except Exception:
            return
        ret_ins = next((ins for ins in mm if ins.name() == "@return"), None)
        if ret_ins is None:
            return
        ret_inputs = ret_ins.inputs()
        scales = [self._scale_from_quantizelinear(ins) for ins in ret_inputs]
        if all(s is None for s in scales):
            scales = [self._scale_from_compiled_chain(ins) for ins in ret_inputs]
        if any(s is not None for s in scales):
            self.output_scales = scales
            print("detected int8 program outputs, dequant scales:", scales)

    def _scale_from_quantizelinear(self, ins):
        if ins.name() != "quantizelinear":
            return None
        ql_inputs = ins.inputs()
        if len(ql_inputs) < 2:
            return None
        scale_src = ql_inputs[1]
        if scale_src.name() in ("multibroadcast", "broadcast"):
            scale_src = scale_src.inputs()[0]
        if scale_src.name() != "@literal":
            return None
        val = np.array(scale_src.get_literal()).reshape(-1)
        if val.size > 0:
            return float(val[0])
        return None

    def _scale_from_compiled_chain(self, ins):
        # Keys detect revisits by id; values keep temporary LACInfer wrappers
        # alive so Python cannot reuse their ids during this traversal.
        seen = {}
        frontier = [ins]
        for _ in range(32):
            nxt = []
            for cur in frontier:
                if id(cur) in seen:
                    continue
                seen[id(cur)] = cur
                name = cur.name()
                if name in ("@param", "@literal"):
                    continue
                try:
                    vals = cur.op().values()
                except Exception:
                    vals = {}
                if vals.get("q_scale") is not None:
                    return float(vals["q_scale"])
                if name == "lac::sync_stream":
                    inputs = cur.inputs()
                    if inputs:
                        nxt.append(inputs[0])
                else:
                    nxt.extend(cur.inputs())
            if not nxt:
                break
            frontier = nxt
        return None

    def _outputs_are_int8(self, result):
        try:
            return any(r.get_shape().type() == lacinfer.shape.type_t.int8_type for r in result)
        except Exception:
            return False

    def _dequantize_outputs(self, result):
        if self.output_scales is None:
            return result
        deq = []
        for i, out in enumerate(result):
            arr = np.array(out)
            scale = self.output_scales[i] if i < len(self.output_scales) else None
            if scale is not None and arr.dtype.kind in ('i', 'u'):
                arr = arr.astype(np.float32) * np.float32(scale)
            deq.append(arr)
        return deq

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

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

        if self._outputs_are_int8(result) and self.output_scales is None:
            print("WARNING: int8 output detected but no scale captured; "
                  "load the uncompiled quantized model or re-run with --forceInt8Output")
        result = self._dequantize_outputs(result)

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

        if boxes is not None:
            # Scale boxes back to original image
            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, angles

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

        # Separate feature maps from angle output
        # Feature maps: 4D tensors with channels >= DFL_CHANNELS + NUM_CLASSES
        # Angle: tensor with total elements = sum of H*W across all feature maps
        feature_maps = []
        angle_out = None
        total_cells = 0

        for out in outputs:
            if out.ndim == 4 and out.shape[1] >= DFL_CHANNELS + NUM_CLASSES:
                feature_maps.append(out)
                total_cells += out.shape[2] * out.shape[3]
            elif out.size == total_cells or (out.ndim >= 1 and out.size > 0):
                if angle_out is None:
                    angle_out = out

        if len(feature_maps) != 3:
            raise ValueError(f"Expected 3 feature maps, got {len(feature_maps)}")

        strides = [self.inputHeight // fm.shape[2] for fm in feature_maps]
        angle_flat = angle_out.flatten() if angle_out is not None else None

        boxes_list, scores_list, classes_list, angles_list = [], [], [], []
        angle_idx = 0

        for fi, fm in enumerate(feature_maps):
            stride = strides[fi]
            grid_h, grid_w = fm.shape[2], fm.shape[3]

            # Extract box DFL channels and class logits
            box_data = fm[:, :DFL_CHANNELS, :, :]  # [1, 64, H, W]
            cls_data = fm[:, DFL_CHANNELS:DFL_CHANNELS + NUM_CLASSES, :, :]  # [1, 15, H, W]

            # DFL decode
            dfl_out = dfl(box_data)  # [1, 4, H, W]
            dfl_flat = dfl_out.transpose(0, 2, 3, 1).reshape(-1, 4)

            # Class scores
            cls_probs = sigmoid(cls_data.transpose(0, 2, 3, 1).reshape(-1, NUM_CLASSES))
            best_cls = cls_probs.argmax(axis=1)
            best_cls_score = cls_probs[np.arange(cls_probs.shape[0]), best_cls]

            # Grid coordinates
            col, row = np.meshgrid(np.arange(grid_w), np.arange(grid_h))
            grid_flat = np.stack([col.flatten(), row.flatten()], axis=1).astype(np.float32)

            # Decode boxes
            x1 = (grid_flat[:, 0] + 0.5 - dfl_flat[:, 0]) * stride
            y1 = (grid_flat[:, 1] + 0.5 - dfl_flat[:, 1]) * stride
            x2 = (grid_flat[:, 0] + 0.5 + dfl_flat[:, 2]) * stride
            y2 = (grid_flat[:, 1] + 0.5 + dfl_flat[:, 3]) * stride

            decoded_boxes = np.stack([x1, y1, x2, y2], axis=1)

            # Get angles
            num_cells = grid_h * grid_w
            if angle_flat is not None:
                cell_angles = angle_flat[angle_idx:angle_idx + num_cells]
                # Convert radians to degrees
                cell_angles = cell_angles / math.pi * 180.0
            else:
                cell_angles = np.zeros(num_cells)
            angle_idx += num_cells

            # Filter by threshold
            keep_mask = best_cls_score >= self.objectThreshold
            if keep_mask.sum() == 0:
                continue

            boxes_list.append(decoded_boxes[keep_mask])
            scores_list.append(best_cls_score[keep_mask])
            classes_list.append(best_cls[keep_mask])
            angles_list.append(cell_angles[keep_mask])

        if not boxes_list:
            return None, None, None, None

        boxes = np.concatenate(boxes_list)
        all_scores = np.concatenate(scores_list)
        all_classes = np.concatenate(classes_list)
        all_angles = np.concatenate(angles_list)

        # NMS using axis-aligned boxes
        keep = nms_boxes(boxes, all_scores, self.nmsThreshold)
        if len(keep) == 0:
            return None, None, None, None

        boxes = boxes[keep]
        all_scores = all_scores[keep]
        all_classes = all_classes[keep]
        all_angles = all_angles[keep]

        return boxes, all_scores, all_classes, all_angles

    def draw_detections(self, image, boxes, scores, class_ids, angles):
        for box, score, cl, angle in zip(boxes, scores, class_ids, angles):
            cl = int(cl)
            label = CLASSES[cl] if cl < len(CLASSES) else str(cl)

            # Compute center and dimensions
            cx = (box[0] + box[2]) / 2
            cy = (box[1] + box[3]) / 2
            w = box[2] - box[0]
            h = box[3] - box[1]

            # Draw rotated rectangle
            rect = ((cx, cy), (w, h), angle)
            box_pts = cv2.boxPoints(rect)
            box_pts = np.intp(box_pts)
            cv2.polylines(image, [box_pts], True, (255, 0, 0), 2)

            # Also draw axis-aligned box for reference
            x1, y1, x2, y2 = [int(_b) for _b in box]
            cv2.putText(image, '{0} {1:.2f}'.format(label, score),
                        (x1, y1 - 6), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2)


def main_func(imgpath, modelpath, calpath, action, modelformat, quantonly,
              savelirs, forceInt8Output, 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 = YOLOv8OBB(modelpath, calpath, action, modelformat, quantonly,
                         savelirs, force_i8_output=forceInt8Output,
                         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, angles = detector.detect(srcimg)

        if boxes is not None:
            dstimg = srcimg.copy()
            detector.draw_detections(dstimg, boxes, scores, class_ids, angles)
            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/ship.jpg', help="image path")
    parser.add_argument('--staticModelPath', type=str, default='../models/f32_model/yolov8n-obb.onnx', help="static onnx filepath")
    parser.add_argument('--objectThreshold', default=0.45, type=float, help='class confidence')
    parser.add_argument('--nmsThreshold', default=0.1, 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("--forceInt8Output", action="store_true", default=False,
                        help="force int8 output when quantizing to int8; outputs are auto-dequantized at inference")
    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", "staticModelPath", "objectThreshold", "nmsThreshold",
        "resPath", "calibrationPath", "action", "modelFormat",
    ]
    flag_specs = ["quantOnly", "saveLirs", "forceInt8Output", ("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)
        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.staticModelPath, args.calibrationPath, action,
              args.modelFormat, quantonly, savelirs, args.forceInt8Output,
              args.objectThreshold, args.nmsThreshold, args.resPath,
              per_channel_ops={"convolution"} if args.per_channel 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)
