from __future__ import annotations

import math
from dataclasses import dataclass
from typing import Iterable, Mapping, Sequence


Vector3 = tuple[float, float, float]
Point2 = tuple[float, float]


def add(a: Vector3, b: Vector3) -> Vector3:
    return (a[0] + b[0], a[1] + b[1], a[2] + b[2])


def subtract(a: Vector3, b: Vector3) -> Vector3:
    return (a[0] - b[0], a[1] - b[1], a[2] - b[2])


def scale(vector: Vector3, factor: float) -> Vector3:
    return (vector[0] * factor, vector[1] * factor, vector[2] * factor)


def dot(a: Vector3, b: Vector3) -> float:
    return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]


def cross(a: Vector3, b: Vector3) -> Vector3:
    return (
        a[1] * b[2] - a[2] * b[1],
        a[2] * b[0] - a[0] * b[2],
        a[0] * b[1] - a[1] * b[0],
    )


def norm(vector: Vector3) -> float:
    return math.sqrt(dot(vector, vector))


def normalize(vector: Vector3, *, tolerance: float = 1.0e-12) -> Vector3:
    length = norm(vector)
    if length <= tolerance:
        raise ValueError("Vetor de direcao do pano possui comprimento nulo.")
    return scale(vector, 1.0 / length)


def interpolate(a: Vector3, b: Vector3, ratio: float) -> Vector3:
    return add(a, scale(subtract(b, a), ratio))


def signed_polygon_area(points: Sequence[Point2]) -> float:
    return 0.5 * sum(
        points[index][0] * points[(index + 1) % len(points)][1]
        - points[(index + 1) % len(points)][0] * points[index][1]
        for index in range(len(points))
    )


def _orientation(a: Point2, b: Point2, c: Point2) -> float:
    return (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0])


def _point_on_segment(point: Point2, a: Point2, b: Point2, tolerance: float) -> bool:
    if abs(_orientation(a, b, point)) > tolerance:
        return False
    return (
        min(a[0], b[0]) - tolerance <= point[0] <= max(a[0], b[0]) + tolerance
        and min(a[1], b[1]) - tolerance <= point[1] <= max(a[1], b[1]) + tolerance
    )


def point_in_polygon(point: Point2, polygon: Sequence[Point2], tolerance: float) -> bool:
    inside = False
    x, y = point
    for index, start in enumerate(polygon):
        end = polygon[(index + 1) % len(polygon)]
        if _point_on_segment(point, start, end, tolerance):
            return True
        if (start[1] > y) != (end[1] > y):
            crossing_x = start[0] + (y - start[1]) * (end[0] - start[0]) / (end[1] - start[1])
            if crossing_x > x:
                inside = not inside
    return inside


def _segments_intersect(a: Point2, b: Point2, c: Point2, d: Point2, tolerance: float) -> bool:
    o1 = _orientation(a, b, c)
    o2 = _orientation(a, b, d)
    o3 = _orientation(c, d, a)
    o4 = _orientation(c, d, b)
    if o1 * o2 < -(tolerance**2) and o3 * o4 < -(tolerance**2):
        return True
    return any(
        (
            abs(value) <= tolerance
            and _point_on_segment(point, first, second, tolerance)
        )
        for value, point, first, second in (
            (o1, c, a, b),
            (o2, d, a, b),
            (o3, a, c, d),
            (o4, b, c, d),
        )
    )


def polygon_is_simple(polygon: Sequence[Point2], tolerance: float) -> bool:
    count = len(polygon)
    for first in range(count):
        a = polygon[first]
        b = polygon[(first + 1) % count]
        for second in range(first + 1, count):
            if second in {first, (first + 1) % count} or (second + 1) % count == first:
                continue
            c = polygon[second]
            d = polygon[(second + 1) % count]
            if _segments_intersect(a, b, c, d, tolerance):
                return False
    return True


def _segment_intersection_parameter(
    start: Point2,
    end: Point2,
    edge_start: Point2,
    edge_end: Point2,
    tolerance: float,
) -> float | None:
    direction = (end[0] - start[0], end[1] - start[1])
    edge = (edge_end[0] - edge_start[0], edge_end[1] - edge_start[1])
    denominator = direction[0] * edge[1] - direction[1] * edge[0]
    if abs(denominator) <= tolerance:
        return None
    offset = (edge_start[0] - start[0], edge_start[1] - start[1])
    ratio = (offset[0] * edge[1] - offset[1] * edge[0]) / denominator
    edge_ratio = (offset[0] * direction[1] - offset[1] * direction[0]) / denominator
    if -tolerance <= ratio <= 1.0 + tolerance and -tolerance <= edge_ratio <= 1.0 + tolerance:
        return min(1.0, max(0.0, ratio))
    return None


def clip_segment_to_polygon(
    start: Point2,
    end: Point2,
    polygon: Sequence[Point2],
    tolerance: float,
) -> list[tuple[float, float]]:
    parameters = [0.0, 1.0]
    for index, edge_start in enumerate(polygon):
        ratio = _segment_intersection_parameter(
            start,
            end,
            edge_start,
            polygon[(index + 1) % len(polygon)],
            tolerance,
        )
        if ratio is not None:
            parameters.append(ratio)
    parameters.sort()
    unique: list[float] = []
    for value in parameters:
        if not unique or abs(value - unique[-1]) > tolerance:
            unique.append(value)
    intervals: list[tuple[float, float]] = []
    for first, second in zip(unique, unique[1:]):
        if second - first <= tolerance:
            continue
        middle = (first + second) * 0.5
        point = (
            start[0] + (end[0] - start[0]) * middle,
            start[1] + (end[1] - start[1]) * middle,
        )
        if point_in_polygon(point, polygon, tolerance):
            intervals.append((first, second))
    return intervals


def scanline_intervals(polygon: Sequence[Point2], transverse: float, tolerance: float) -> list[tuple[float, float]]:
    intersections: list[float] = []
    query = transverse
    if any(abs(point[1] - query) <= tolerance for point in polygon):
        query += tolerance * 8.0
    for index, start in enumerate(polygon):
        end = polygon[(index + 1) % len(polygon)]
        if (start[1] > query) == (end[1] > query):
            continue
        ratio = (query - start[1]) / (end[1] - start[1])
        intersections.append(start[0] + (end[0] - start[0]) * ratio)
    intersections.sort()
    return [
        (intersections[index], intersections[index + 1])
        for index in range(0, len(intersections) - 1, 2)
        if intersections[index + 1] - intersections[index] > tolerance
    ]


@dataclass(frozen=True)
class PanelGeometry:
    points: tuple[Vector3, ...]
    origin: Vector3
    normal: Vector3
    distribution: Vector3
    transverse: Vector3
    polygon: tuple[Point2, ...]
    area: float
    z_min: float
    z_max: float
    tolerance: float

    def project(self, point: Vector3) -> Point2:
        offset = subtract(point, self.origin)
        return (dot(offset, self.distribution), dot(offset, self.transverse))

    def plane_distance(self, point: Vector3) -> float:
        return dot(subtract(point, self.origin), self.normal)


def node_point(node: object) -> Vector3:
    return (float(getattr(node, "x")), float(getattr(node, "y")), float(getattr(node, "z")))


def build_panel_geometry(
    nodes_by_id: Mapping[int, object],
    node_ids: Sequence[int],
    distribution_edge: int,
    distribution_mode: str,
    normal_reversed: bool,
) -> PanelGeometry:
    points = tuple(node_point(nodes_by_id[node_id]) for node_id in node_ids)
    extent = max(
        (norm(subtract(first, second)) for first in points for second in points),
        default=1.0,
    )
    tolerance = max(1.0e-8, extent * 1.0e-8)
    newell = (
        sum((points[index][1] - points[(index + 1) % len(points)][1]) * (points[index][2] + points[(index + 1) % len(points)][2]) for index in range(len(points))),
        sum((points[index][2] - points[(index + 1) % len(points)][2]) * (points[index][0] + points[(index + 1) % len(points)][0]) for index in range(len(points))),
        sum((points[index][0] - points[(index + 1) % len(points)][0]) * (points[index][1] + points[(index + 1) % len(points)][1]) for index in range(len(points))),
    )
    try:
        normal = normalize(newell, tolerance=tolerance**2)
    except ValueError:
        normal = None
        for first in range(len(points) - 2):
            candidate = cross(
                subtract(points[first + 1], points[first]),
                subtract(points[first + 2], points[first]),
            )
            if norm(candidate) > tolerance**2:
                normal = normalize(candidate)
                break
        if normal is None:
            raise ValueError("Contorno do pano possui area nula.")
    if normal_reversed:
        normal = scale(normal, -1.0)
    origin = points[0]
    if any(abs(dot(subtract(point, origin), normal)) > tolerance for point in points[1:]):
        raise ValueError("Contorno do pano nao e coplanar.")
    edge_start = points[distribution_edge]
    edge_end = points[(distribution_edge + 1) % len(points)]
    edge = normalize(subtract(edge_end, edge_start), tolerance=tolerance)
    distribution = edge if distribution_mode == "parallel" else normalize(cross(normal, edge))
    transverse = normalize(cross(normal, distribution))
    polygon = tuple(
        (dot(subtract(point, origin), distribution), dot(subtract(point, origin), transverse))
        for point in points
    )
    area = abs(signed_polygon_area(polygon))
    if area <= tolerance**2:
        raise ValueError("Contorno do pano possui area nula.")
    if not polygon_is_simple(polygon, tolerance):
        raise ValueError("Contorno do pano possui cruzamento entre lados.")
    return PanelGeometry(
        points=points,
        origin=origin,
        normal=normal,
        distribution=distribution,
        transverse=transverse,
        polygon=polygon,
        area=area,
        z_min=min(point[2] for point in points),
        z_max=max(point[2] for point in points),
        tolerance=tolerance,
    )


def validate_panel_geometries(nodes_by_id: Mapping[int, object], panels: Iterable[object]) -> None:
    for panel in panels:
        try:
            build_panel_geometry(
                nodes_by_id,
                panel.node_ids,
                panel.distribution_edge,
                panel.distribution_mode,
                panel.normal_reversed,
            )
        except (KeyError, ValueError) as exc:
            raise ValueError(f"Pano {panel.id}: {exc}") from exc
