import cv2
import json


class FrameRectifier:
    def __init__(self, json_path="rotation_config.json"):
        self.mode = "disabled"
        self.rotation_angle = 0.0
        self.flip_x = False
        self.flip_y = False

        try:
            with open(json_path, "r") as f:
                config = json.load(f)
        except FileNotFoundError:
            print(f"[Info] 未找到方向配置文件 {json_path}，不做旋转/翻转。")
            return
        except Exception as exc:
            print(f"[Error] 读取配置文件失败: {exc}")
            return

        self.rotation_angle = float(config.get("rotation_angle", config.get("angle", 0)))
        self.flip_x = self._as_bool(config.get("flip_x", config.get("x_flip", False)))
        self.flip_y = self._as_bool(config.get("flip_y", config.get("y_flip", False)))
        self.mode = "simple"
        print(
            "[Init] 加载简单方向配置成功: "
            f"rotation_angle={self.rotation_angle:g}, "
            f"flip_x={self.flip_x}, flip_y={self.flip_y}"
        )

    @staticmethod
    def _as_bool(value):
        if isinstance(value, str):
            return value.strip().lower() in ("1", "true", "yes", "on")
        return bool(value)

    def _rotate_simple(self, frame):
        angle = self.rotation_angle % 360
        if angle == 0:
            return frame
        if angle == 90:
            return cv2.rotate(frame, cv2.ROTATE_90_COUNTERCLOCKWISE)
        if angle == 180:
            return cv2.rotate(frame, cv2.ROTATE_180)
        if angle == 270:
            return cv2.rotate(frame, cv2.ROTATE_90_CLOCKWISE)

        h, w = frame.shape[:2]
        center = ((w - 1) / 2.0, (h - 1) / 2.0)
        matrix = cv2.getRotationMatrix2D(center, self.rotation_angle, 1.0)
        cos_v = abs(matrix[0, 0])
        sin_v = abs(matrix[0, 1])
        new_w = int((h * sin_v) + (w * cos_v))
        new_h = int((h * cos_v) + (w * sin_v))
        matrix[0, 2] += (new_w - w) / 2.0
        matrix[1, 2] += (new_h - h) / 2.0
        return cv2.warpAffine(frame, matrix, (new_w, new_h), flags=cv2.INTER_LINEAR)

    def rectify(self, frame):
        if frame is None or self.mode == "disabled":
            return frame

        frame = self._rotate_simple(frame)
        if self.flip_x and self.flip_y:
            return cv2.flip(frame, -1)
        if self.flip_x:
            return cv2.flip(frame, 1)
        if self.flip_y:
            return cv2.flip(frame, 0)
        return frame
