import math
import matplotlib.pyplot as plt


def graham_scan(points):
    """
    Побудова опуклої оболонки методом Грехема.
    points: список кортежів (x, y)
    Повертає список точок опуклої оболонки у порядку проти годинникової стрілки.
    """
    points = list(set(points))  # прибираємо дублікати
    if len(points) < 3:
        return points

    # 1. Знаходимо опорну точку: мінімальний y, при рівності — мінімальний x
    p0 = min(points, key=lambda p: (p[1], p[0]))

    # 2. Функції для полярного кута та квадрата відстані відносно p0
    def polar_angle(p):
        dx = p[0] - p0[0]
        dy = p[1] - p0[1]
        return math.atan2(dy, dx)

    def dist_sq(p):
        dx = p[0] - p0[0]
        dy = p[1] - p0[1]
        return dx * dx + dy * dy

    # 3. Сортуємо решту точок за кутом; при однаковому куті — за відстанню
    sorted_points = sorted(
        [p for p in points if p != p0],
        key=lambda p: (polar_angle(p), dist_sq(p))
    )

    # 4. При однаковому куті залишаємо тільки найдальшу точку
    filtered = []
    i = 0
    n = len(sorted_points)
    while i < n:
        j = i
        while j < n - 1 and math.isclose(
            polar_angle(sorted_points[j]), polar_angle(sorted_points[j + 1]), abs_tol=1e-9
        ):
            j += 1
        filtered.append(sorted_points[j])
        i = j + 1

    if len(filtered) < 2:
        return [p0] + filtered

    # 5. Векторний добуток для перевірки напрямку повороту
    def cross(o, a, b):
        return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0])

    # 6. Основний прохід стеком
    stack = [p0, filtered[0], filtered[1]]

    for p in filtered[2:]:
        while len(stack) > 1 and cross(stack[-2], stack[-1], p) <= 0:
            stack.pop()
        stack.append(p)

    return stack


def plot_convex_hull(points, hull):
    """
    Візуалізація точок та їх опуклої оболонки.
    """
    xs, ys = zip(*points)
    hull_xs, hull_ys = zip(*hull)

    # Замикаємо оболонку, повертаючись до першої точки
    hull_xs = hull_xs + (hull_xs[0],)
    hull_ys = hull_ys + (hull_ys[0],)

    plt.figure(figsize=(6, 6))

    plt.scatter(xs, ys, color='blue', label='Точки', zorder=3)
    plt.plot(hull_xs, hull_ys, color='red', linewidth=2, label='Опукла оболонка', zorder=2)
    plt.scatter(hull_xs, hull_ys, color='red', zorder=4)

    for x, y in points:
        plt.annotate(f"({x},{y})", (x, y), textcoords="offset points", xytext=(5, 5), fontsize=8)

    plt.title("Опукла оболонка (метод Грехема)")
    plt.xlabel("X")
    plt.ylabel("Y")
    plt.legend()
    plt.grid(True, linestyle='--', alpha=0.5)
    plt.axis('equal')
    plt.show()


if __name__ == "__main__":
    # Приклад довільної множини точок
    points = [
        (0, 0), (1, 1), (2, 2), (2, 0),
        (0, 2), (3, 1), (1, 3)
    ]

    hull = graham_scan(points)

    print("Вихідні точки:")
    for p in points:
        print(f"  {p}")

    print("\nОпукла оболонка (проти годинникової стрілки):")
    for p in hull:
        print(f"  {p}")

    plot_convex_hull(points, hull)
