import numpy as np

from scipy.spatial import ConvexHull

from kinematic_tracker.types import FVT

from .create_polygon import create_polygon
from .poly_area import get_poly_area


def giou_yaw(cuboid: FVT, cuboid2: FVT) -> float:
    poly = create_polygon(cuboid)
    poly2 = create_polygon(cuboid2)
    ha, hb = cuboid[8], cuboid2[8]
    za, zb = cuboid[2], cuboid2[2]
    overlap_height = max(
        0, min([(za + ha / 2) - (zb - hb / 2), (zb + hb / 2) - (za - ha / 2), ha, hb])
    )
    union_height = max([(za + ha / 2) - (zb - hb / 2), (zb + hb / 2) - (za - ha / 2), ha, hb])

    # compute intersection and union
    inter_vol = poly.intersection(poly2).area * overlap_height
    union_vol = cuboid[7] * cuboid[6] * ha + cuboid2[7] * cuboid2[6] * hb - inter_vol
    # compute the convex area
    merged = np.concatenate((poly.exterior.coords, poly2.exterior.coords))
    convex_hull = ConvexHull(merged)
    convex_corners = merged[convex_hull.vertices]
    convex_area = get_poly_area(convex_corners)
    convex_vol = convex_area * union_height

    # compute giou
    giou = inter_vol / union_vol - (convex_vol - union_vol) / convex_vol
    return (giou + 1.0) / 2.0
