import math
import torch


def adjust_intrinsics_crop(K, crop_size, bbox, max_crop_area):
    """
    Adjust intrinsics to render the crop 
    
    Args:
        sample: intrinsics parameters
        crop_size: size of the crop
        bbox: 2D bounding box
        max_crop_area: Maximum crop area (to assure 

    Returns: new crop size, adjusted intrinsics, and original intrinsics

    """
    l, t, r, b = bbox
    crop_H, crop_W = crop_size
    area_ratio_sqrt = math.sqrt(max_crop_area / (crop_H * crop_W))
    crop_size = (crop_size * area_ratio_sqrt)
    crop_size = crop_size.int().numpy().tolist()
    intrinsics = torch.Tensor(K)
    intrinsics[0, 2] -= l
    intrinsics[1, 2] -= t
    off_intrinsics = intrinsics.clone()
    intrinsics[:2] *= area_ratio_sqrt
    return crop_size, intrinsics, off_intrinsics