from functools import partial

import cv2
import numpy as np
from iteration_utilities import starfilter, first

from cv_analysis.utils.filters import is_large_enough, is_filled, is_boxy
from cv_analysis.utils.visual_logging import vizlogger


def is_likely_redaction(contour, hierarchy, min_area):
    return is_filled(hierarchy) and is_boxy(contour) and is_large_enough(contour, min_area)


def find_redactions(image: np.array, min_normalized_area=200000):
    vizlogger.debug(image, "redactions01_start.png")
    min_normalized_area /= 200  # Assumes 200 DPI PDF -> image conversion resolution

    if len(image.shape) > 2:
        gray = ~cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    else:
        gray = ~image
    vizlogger.debug(gray, "redactions02_gray.png")
    blurred = cv2.GaussianBlur(gray, (5, 5), 1)
    vizlogger.debug(blurred, "redactions03_blur.png")
    thresh = cv2.threshold(blurred, 252, 255, cv2.THRESH_BINARY)[1]
    vizlogger.debug(blurred, "redactions04_threshold.png")

    contours, hierarchies = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)

    try:
        contours = map(
            first,
            starfilter(
                partial(is_likely_redaction, min_area=min_normalized_area),
                zip(contours, hierarchies[0]),
            ),
        )
        return list(contours)
    except:
        return []
