"""Full-resolution orthographic rendering and screen-space orbit controls."""

import ctypes
from dataclasses import dataclass, field
from functools import lru_cache
from pathlib import Path
import sys

import numpy as np
from PIL import Image


def initial_basis():
    yaw, pitch = -.84, .62
    right = np.array((np.cos(yaw), -np.sin(yaw), 0.))
    up = np.array((np.sin(pitch)*np.sin(yaw), np.sin(pitch)*np.cos(yaw), np.cos(pitch)))
    return np.column_stack((right, -up, np.cross(right, up)))


@dataclass
class Camera:
    basis: np.ndarray = field(default_factory=initial_basis)
    zoom: float = 1.35
    pan: np.ndarray = field(default_factory=lambda: np.zeros(2))

    def orbit(self, dx, dy):
        magnitude = np.hypot(dx, dy)
        if magnitude == 0:
            return
        axis = np.array((dy, -dx, 0.)) / magnitude
        angle = magnitude * .013
        x, y, z = axis
        cross = np.array(((0., -z, y), (z, 0., -x), (-y, x, 0.)))
        spin = np.eye(3) + np.sin(angle)*cross + (1.-np.cos(angle))*(cross @ cross)
        self.basis = self.basis @ spin

    def scroll(self, steps, x, y, width, height):
        old = self.zoom
        self.zoom = float(np.clip(old * 1.16**steps, .12, 50.))
        cursor = np.array((x-width*.5, y-height*.5))
        self.pan = cursor + (self.pan-cursor) * (self.zoom / old)

    def snapshot(self):
        return self.basis.astype(np.float32), self.zoom, tuple(self.pan)


@dataclass
class Mesh:
    nodes: np.ndarray
    normals: np.ndarray
    triangles: np.ndarray
    materials: np.ndarray
    edges: np.ndarray


def mesh(shape, *, quick=False, limits=None):
    from exterior import bounds, members
    from OCP.BRep import BRep_Tool
    from OCP.BRepAdaptor import BRepAdaptor_Curve
    from OCP.BRepLib import BRepLib_ToolTriangulatedShape
    from OCP.BRepMesh import BRepMesh_IncrementalMesh
    from OCP.GCPnts import GCPnts_QuasiUniformDeflection
    from OCP.TopAbs import TopAbs_EDGE, TopAbs_FACE, TopAbs_REVERSED, TopAbs_SHELL, TopAbs_SOLID
    from OCP.TopLoc import TopLoc_Location
    from OCP.TopoDS import TopoDS
    from OCP.TopTools import TopTools_IndexedMapOfShape

    if limits is None:
        limits = bounds(shape)
    center = limits.mean(axis=0)
    span = max(np.linalg.norm(np.ptp(limits, axis=0)), 1e-9)
    deflection, angle = (span/850, .28) if quick else (span/5000, .065)
    BRepMesh_IncrementalMesh(shape, max(1e-7, deflection), False, angle, True)
    groups = members(shape, TopAbs_SOLID) or members(shape, TopAbs_SHELL) or [shape]
    seen, seams = TopTools_IndexedMapOfShape(), TopTools_IndexedMapOfShape()
    nodes, normals, indices, materials, offset = [], [], [], [], 0
    segments, sampled_edges = [], TopTools_IndexedMapOfShape()
    for group_index, group in enumerate(groups):
        for item in members(group, TopAbs_FACE):
            if seen.Contains(item):
                continue
            seen.Add(item)
            face, location = TopoDS.Face_s(item), TopLoc_Location()
            triangulation = BRep_Tool.Triangulation_s(face, location)
            if triangulation is None or not triangulation.NbTriangles():
                continue
            count = triangulation.NbNodes()
            xyz = np.array([triangulation.Node(i).Coord() for i in range(1, count+1)])
            rotation = None
            if not location.IsIdentity():
                transform = location.Transformation()
                rotation = np.array([[transform.Value(r, c) for c in (1, 2, 3)] for r in (1, 2, 3)])
                xyz = xyz @ rotation.T + transform.TranslationPart().Coord()
            triangles = np.array([triangulation.Triangle(i).Get()
                                  for i in range(1, triangulation.NbTriangles()+1)], dtype=np.int32) - 1
            reverse = face.Orientation() == TopAbs_REVERSED
            if reverse:
                triangles = triangles[:, (0, 2, 1)]
            try:
                BRepLib_ToolTriangulatedShape.ComputeNormals_s(face, triangulation)
                normal = np.array([triangulation.Normal(i).Coord() for i in range(1, count+1)])
                if rotation is not None:
                    normal = normal @ rotation.T
                    normal /= np.linalg.norm(normal, axis=1, keepdims=True)
                vectors = xyz[triangles]
                winding = np.cross(vectors[:,1]-vectors[:,0], vectors[:,2]-vectors[:,0])
                if np.sum(winding * normal[triangles[:,0]]) < 0:
                    normal *= -1
            except RuntimeError:
                vectors = xyz[triangles]
                winding = np.cross(vectors[:,1]-vectors[:,0], vectors[:,2]-vectors[:,0])
                normal = np.zeros_like(xyz)
                for column in triangles.T:
                    np.add.at(normal, column, winding)
                normal /= np.maximum(np.linalg.norm(normal, axis=1, keepdims=True), 1e-20)
            nodes.append(((xyz-center)/span).astype(np.float32))
            normals.append(normal.astype(np.float32))
            indices.append(triangles+offset)
            materials.append(np.full(len(triangles), group_index, dtype=np.int32))
            offset += len(xyz)
            for item in members(face, TopAbs_EDGE):
                edge = TopoDS.Edge_s(item)
                if BRep_Tool.IsClosed_s(edge, face):
                    seams.Add(item)
                elif quick and not sampled_edges.Contains(item) and not BRep_Tool.Degenerated_s(edge):
                    polygon = BRep_Tool.PolygonOnTriangulation_s(edge, triangulation, location)
                    if polygon is not None and polygon.NbNodes() > 1:
                        sampled_edges.Add(item)
                        ids = [polygon.Node(i)-1 for i in range(1, polygon.NbNodes()+1)]
                        points = xyz[ids]
                        segments.append((item, np.stack((points[:-1], points[1:]), axis=1)))
    if not nodes:
        raise ValueError("STEP 无法生成三维预览。")
    if quick:
        segments = [points for item, points in segments if not seams.Contains(item)]
    else:
        for item in members(shape, TopAbs_EDGE):
            edge = TopoDS.Edge_s(item)
            if seams.Contains(edge) or BRep_Tool.Degenerated_s(edge):
                continue
            try:
                sampled = GCPnts_QuasiUniformDeflection(BRepAdaptor_Curve(edge), max(span/6500, 1e-7))
                if sampled.IsDone() and sampled.NbPoints() > 1:
                    xyz = np.array([sampled.Value(i).Coord() for i in range(1, sampled.NbPoints()+1)])
                    segments.append(np.stack((xyz[:-1], xyz[1:]), axis=1))
            except RuntimeError:
                continue
    edges = ((np.concatenate(segments)-center)/span).astype(np.float32) if segments else np.empty((0,2,3), np.float32)
    return Mesh(np.concatenate(nodes), np.concatenate(normals), np.concatenate(indices),
                np.concatenate(materials), edges)


@lru_cache(maxsize=1)
def renderer():
    path = Path(__file__).with_name("raster.dll" if sys.platform == "win32" else "raster.so")
    library = ctypes.CDLL(str(path))
    floats = np.ctypeslib.ndpointer(np.float32, flags="C_CONTIGUOUS")
    ints = np.ctypeslib.ndpointer(np.int32, flags="C_CONTIGUOUS")
    pixels = np.ctypeslib.ndpointer(np.uint8, flags="C_CONTIGUOUS")
    library.draw_faces.argtypes = (floats, floats, ints, ints, ctypes.c_size_t,
                                   pixels, floats, ctypes.c_int, ctypes.c_int, pixels)
    library.draw_faces.restype = None
    library.draw_edges.argtypes = (floats, ctypes.c_size_t, pixels, floats, ctypes.c_int,
                                   ctypes.c_int, pixels, ctypes.c_float, ctypes.c_int)
    library.draw_edges.restype = None
    return library


COLORS = ((73,137,200),(226,155,82),(71,163,147),(184,125,183),
          (206,111,103),(141,157,91),(88,166,191),(159,132,100),
          (121,135,202),(205,136,151),(116,158,117),(114,143,159))


def image(data, width, height, camera, palette, mode, edges, colored):
    width, height = max(2, width), max(2, height)
    background = bytes.fromhex(palette["view"].lstrip("#"))
    rgba = int.from_bytes(background + b"\xff", "little")
    pixels = np.full((height, width), rgba, dtype="<u4").view(np.uint8).reshape(height, width, 4)
    if data is None:
        return Image.fromarray(pixels)
    basis, zoom, pan = camera
    scale = min(width, height)*zoom
    origin = np.array((width*.5+pan[0], height*.5+pan[1]), dtype=np.float32)
    raster = renderer()
    depth = np.empty((height, width), np.float32)
    if mode != "wire":
        xyz = data.nodes @ basis
        xyz[:,:2] *= scale
        xyz[:,:2] += origin
        facing, up, right = basis[:,2], -basis[:,1], basis[:,0]
        key = np.maximum(data.normals @ (facing*.74+up*.56-right*.36), 0)
        fill = np.maximum(data.normals @ (facing*.66-up*.52+right*.43), 0)
        light = np.clip(.24+.65*key+.17*fill, 0, 1)
        if mode == "hidden":
            shades = np.tile(np.asarray(tuple(background)*2, np.uint8), (data.materials.max()+1, 1))
        elif colored:
            colors = np.asarray(COLORS, dtype=np.float32)[np.arange(data.materials.max()+1) % len(COLORS)]
            shades = np.column_stack((colors*.33, colors*.52 + 255*.48)).astype(np.uint8)
        else:
            shades = np.asarray([(*palette["shade"], *palette["light"])]*(data.materials.max()+1), np.uint8)
        raster.draw_faces(xyz, light, data.triangles, data.materials, len(data.triangles),
                          pixels, depth, width, height, shades)
    if (mode == "shaded" and edges) or mode in ("wire", "hidden"):
        lines = data.edges @ basis
        lines[...,:2] *= scale
        lines[...,:2] += origin
        raster.draw_edges(lines, len(lines), pixels, depth, width, height,
                          np.frombuffer(bytes.fromhex(palette["edge"].lstrip("#")), dtype=np.uint8),
                          1.3/scale, int(mode == "wire"))
    return Image.fromarray(pixels)
