"""Directional CAD envelope. Meshes never enter the modeling pipeline."""

from dataclasses import dataclass, field

import numpy as np

from OCP.BRep import BRep_Builder, BRep_Tool
from OCP.BRepAdaptor import BRepAdaptor_Surface
from OCP.BRepAlgoAPI import BRepAlgoAPI_Common, BRepAlgoAPI_Cut, BRepAlgoAPI_Fuse, BRepAlgoAPI_Splitter
from OCP.BRepBuilderAPI import BRepBuilderAPI_MakeFace, BRepBuilderAPI_MakeSolid
from OCP.BRepCheck import BRepCheck_Analyzer
from OCP.BRepClass import BRepClass_FaceClassifier
from OCP.BRepClass3d import BRepClass3d
from OCP.BRepGProp import BRepGProp
from OCP.BRepLib import BRepLib
from OCP.BRepPrimAPI import BRepPrimAPI_MakeCylinder, BRepPrimAPI_MakeHalfSpace, BRepPrimAPI_MakePrism
from OCP.BRepTools import BRepTools
from OCP.GeomAbs import (GeomAbs_BSplineSurface, GeomAbs_BezierSurface, GeomAbs_Cone, GeomAbs_Cylinder, GeomAbs_Plane, GeomAbs_Sphere,
                        GeomAbs_SurfaceOfExtrusion, GeomAbs_Torus)
from OCP.GProp import GProp_GProps
from OCP.ShapeFix import ShapeFix_Face
from OCP.ShapeUpgrade import ShapeUpgrade_UnifySameDomain
from OCP.TopAbs import TopAbs_IN, TopAbs_REVERSED, TopAbs_WIRE
from OCP.TopoDS import TopoDS, TopoDS_Compound, TopoDS_Shell
from OCP.TopTools import TopTools_ListOfShape
from OCP.gp import gp_Ax2, gp_Dir, gp_Pln, gp_Pnt, gp_Pnt2d, gp_Vec

from exterior import (Opening, ShellError, TOL, TopAbs_FACE, TopAbs_SHELL, TopAbs_SOLID,
                      bounds, is_trim, members, offset, plane_for_solid, read_step,
                      step_bytes, volume)


def shape_list(shapes):
    values = TopTools_ListOfShape()
    for shape in shapes:
        values.Append(shape)
    return values


def compound(shapes):
    if len(shapes) == 1:
        return shapes[0]
    builder, result = BRep_Builder(), TopoDS_Compound()
    builder.MakeCompound(result)
    for shape in shapes:
        builder.Add(result, shape)
    return result


def smoothed(shape):
    unify = ShapeUpgrade_UnifySameDomain(shape, True, True)
    unify.SetLinearTolerance(TOL)
    unify.Build()
    result = unify.Shape()
    return result if BRepCheck_Analyzer(result).IsValid() else shape


def operate(kind, base, tools, label):
    operation = kind()
    operation.SetArguments(shape_list(base))
    operation.SetTools(shape_list(tools))
    operation.SetNonDestructive(True)
    operation.SetRunParallel(len(base) + len(tools) >= 8)
    operation.SetFuzzyValue(TOL)
    operation.Build()
    if not operation.IsDone() or operation.Shape().IsNull():
        raise ShellError(f"{label}失败。")
    return operation.Shape()


def fused(items, label):
    if len(items) == 1:
        return items[0]
    return smoothed(operate(BRepAlgoAPI_Fuse, items[:1], items[1:], label))


def solids(shape, label):
    result = members(shape, TopAbs_SOLID)
    if not result or any(not BRepCheck_Analyzer(item).IsValid() or volume(item) <= 0 for item in result):
        raise ShellError(f"{label}没有形成有效的闭合 CAD 实体。")
    if len(members(shape, TopAbs_FACE)) != len(members(compound(result), TopAbs_FACE)):
        raise ShellError(f"{label}产生了游离曲面。")
    return result


def support(normal, point):
    return BRepBuilderAPI_MakeFace(gp_Pln(gp_Pnt(*point), gp_Dir(*normal))).Face()


def halfspace(normal, height):
    return BRepPrimAPI_MakeHalfSpace(support(normal, normal * height),
                                     gp_Pnt(*(normal * (height - 1.0)))).Solid()


def split_face(face, plane):
    result = operate(BRepAlgoAPI_Splitter, [face], [plane], "扫掠面分区")
    pieces = [TopoDS.Face_s(item) for item in members(result, TopAbs_FACE)]
    if len(pieces) < 2:
        return ()
    def area(shape):
        props = GProp_GProps()
        BRepGProp.SurfaceProperties_s(shape, props, 1e-7)
        return props.Mass()
    original_area = area(face)
    if abs(sum(area(piece) for piece in pieces) - original_area) > max(TOL, original_area * 1e-5):
        raise ShellError("原生分区面积超出公差")
    return pieces


def partition(face, planes):
    pieces = [face]
    for plane in planes:
        pieces = [piece for item in pieces for piece in (split_face(item, plane) or [item])]
    return pieces


def outward_alignment(face, fit, vector, u, v):
    point, du, dv = gp_Pnt(), gp_Vec(), gp_Vec()
    fit.D1(u, v, point, du, dv)
    cross = du.Crossed(dv)
    if cross.Magnitude() <= 1e-15:
        return 0.
    sign = -1 if face.Orientation() == TopAbs_REVERSED else 1
    return sign * (np.asarray(cross.Coord()) @ vector) / cross.Magnitude()


def silhouette(face, fit, vector):
    """Cut along exact grazing curves for the common analytic surface types."""
    kind = fit.GetType()
    if kind == GeomAbs_Sphere:
        point = np.asarray(fit.Sphere().Location().Coord())
        return partition(face, [support(vector, point)]), True
    if kind == GeomAbs_Torus:
        torus = fit.Torus()
        point = np.asarray(torus.Location().Coord())
        axis = np.asarray(torus.Axis().Direction().Coord())
        axial = vector @ axis
        if abs(axial) > 1-1e-12:
            return partition(face, [support(axis, point)]), True
        if abs(axial) < 1e-10:
            extent = 2*torus.MinorRadius()
            cylinder = BRepPrimAPI_MakeCylinder(
                gp_Ax2(gp_Pnt(*(point-axis*extent)), gp_Dir(*axis)),
                torus.MajorRadius(), 2*extent).Face()
            return partition(face, [support(vector, point), cylinder]), True
        return [face], False
    if kind in (GeomAbs_Cylinder, GeomAbs_Cone):
        analytic = fit.Cylinder() if kind == GeomAbs_Cylinder else fit.Cone()
        axis = np.asarray(analytic.Axis().Direction().Coord())
        frame = analytic.Position()
        x = np.asarray(frame.XDirection().Coord())
        y = np.asarray(frame.YDirection().Coord())
        direction = np.array((vector @ x, vector @ y))
        transverse = np.linalg.norm(direction)
        if transverse < 1e-10:
            return ([] if kind == GeomAbs_Cylinder else [face]), True
        slope = np.tan(analytic.SemiAngle()) if kind == GeomAbs_Cone else 0.
        target = (vector @ axis)*slope/transverse
        if abs(target) >= 1:
            return [face], True
        phase = np.arctan2(direction[1], direction[0])
        roots = (phase + np.arccos(target), phase - np.arccos(target))
        if kind == GeomAbs_Cylinder:
            roots = roots[:1]
        point = np.asarray(analytic.Location().Coord())
        planes = [support(-np.sin(root)*x + np.cos(root)*y, point) for root in roots]
        return partition(face, planes), True
    return [face], False


def tangent_spline(surface, vector):
    """Prove that projection collapses a complete spline parameter direction."""
    poles = np.array([[surface.Pole(u, v).Coord() for v in range(1, surface.NbVPoles()+1)]
                      for u in range(1, surface.NbUPoles()+1)])
    weights = np.array([[surface.Weight(u, v) for v in range(1, surface.NbVPoles()+1)]
                        for u in range(1, surface.NbUPoles()+1)])
    # Identical transverse poles and weights along an axis make the projected
    # rational surface independent of that parameter, including trimmed patches.
    for axis in (0, 1):
        points, values = np.moveaxis(poles, axis, 0), np.moveaxis(weights, axis, 0)
        delta = points - points[:1]
        if np.all(values == values[:1]) and np.max(np.linalg.norm(np.cross(delta, vector), axis=2)) <= 1e-10:
            return True
    return False


def sweep(face, vector, reach, retries=3, prepared=False, monotone=False, closed=True, budget=None):
    if budget is None:
        budget = [64]
    budget[0] -= 1
    if budget[0] < 0:
        raise ShellError("可见曲面的扫掠未能闭合")
    fit = BRepAdaptor_Surface(face)
    kind = fit.GetType()
    if kind == GeomAbs_Plane:
        normal = np.asarray(fit.Plane().Axis().Direction().Coord())
        alignment = float(normal @ vector)
        if face.Orientation() == TopAbs_REVERSED:
            alignment = -alignment
        if abs(alignment) < 1e-10 or (closed and alignment > 0):
            return []
    elif kind == GeomAbs_SurfaceOfExtrusion:
        if abs(np.asarray(fit.Direction().Coord()) @ vector) > 1-1e-12:
            return []
    elif not prepared:
        if kind == GeomAbs_BSplineSurface and tangent_spline(fit.BSpline(), vector):
            return []
        if kind == GeomAbs_BezierSurface and tangent_spline(fit.Bezier(), vector):
            return []
        try:
            pieces, monotone = silhouette(face, fit, vector)
        except ShellError:
            pieces, monotone = [face], False
        return [item for piece in pieces
                for item in sweep(piece, vector, reach, retries, True, monotone, closed, budget)]
    if monotone and closed:
        umin, umax, vmin, vmax = BRepTools.UVBounds_s(face)
        # Split trimmed periodic faces can have broad UV bounds. Verify the
        # sign at actual points within the face before omitting a back patch.
        signs = []
        for us in (.2, .5, .8):
            for vs in (.2, .5, .8):
                u, v = umin + (umax-umin)*us, vmin + (vmax-vmin)*vs
                if BRepClass_FaceClassifier(face, gp_Pnt2d(u, v), TOL).State() == TopAbs_IN:
                    signs.append(outward_alignment(face, fit, vector, u, v))
        if signs and min(signs) > 1e-10:
            return []
    try:
        prism = BRepPrimAPI_MakePrism(face, gp_Vec(*(vector * reach)), False, True).Shape()
        pieces = members(prism, TopAbs_SOLID)
        if len(pieces) == 1:
            item = TopoDS.Solid_s(pieces[0])
            if BRepLib.OrientClosedSolid_s(item) and BRepCheck_Analyzer(item).IsValid():
                if volume(item) > TOL**3:
                    return [item]
    except RuntimeError:
        pass
    if retries:
        # Retry localized patches of the actual CAD face. This preserves trims
        # and the supporting curve or surface on each piece.
        box = bounds(face)
        axes = np.eye(3)
        first = np.cross(vector, axes[np.argmin(abs(vector))])
        first /= np.linalg.norm(first)
        second = np.cross(vector, first)
        # A splitter parallel to the sweep keeps its children in different
        # projected regions. Try the other axes if a child cannot be swept.
        candidates = (first, second, *axes[np.argsort(np.ptp(box, axis=0))[::-1]])
        used = []
        for axis in candidates:
            if abs(axis) @ np.ptp(box, axis=0) <= 50*TOL:
                continue
            if any(abs(axis @ previous) > 1 - 1e-12 for previous in used):
                continue
            used.append(axis)
            try:
                pieces = split_face(face, support(axis, box.mean(axis=0)))
                if pieces:
                    return [item for piece in pieces
                            for item in sweep(piece, vector, reach, retries-1, True, monotone, closed, budget)]
            except (ShellError, RuntimeError):
                if budget[0] < 0:
                    break
    raise ShellError("可见曲面的扫掠未能闭合")


def exterior_solid(part):
    if len(members(part, TopAbs_SHELL)) == 1:
        return part
    outer = BRepClass3d.OuterShell_s(TopoDS.Solid_s(part))
    if outer.IsNull():
        raise ShellError("无法识别零件的外壳。")
    filled = BRepBuilderAPI_MakeSolid(outer).Solid()
    if not BRepLib.OrientClosedSolid_s(filled) or not BRepCheck_Analyzer(filled).IsValid():
        raise ShellError("填充内部空腔后零件无效。")
    return filled


def sweep_parts(parts, opening, reach, trim, progress):
    vector = opening.normal
    swept = []
    for part_index, part in enumerate(parts, 1):
        progress(.10 + .40*(part_index-1)/len(parts), f"处理零件 {part_index}/{len(parts)} 的原生曲面")
        part = exterior_solid(part)
        projected = [part]
        for face_index, item in enumerate(members(part, TopAbs_FACE), 1):
            face = TopoDS.Face_s(item)
            try:
                fit = BRepAdaptor_Surface(face)
                if fit.GetType() == GeomAbs_Plane:
                    # A closed perforation in a roof plane is interior to the
                    # visible outline. Reuse the exact original outer wire.
                    outer = BRepTools.OuterWire_s(face)
                    if not outer.IsNull() and len(members(face, TopAbs_WIRE)) > 1:
                        maker = BRepBuilderAPI_MakeFace(fit.Plane(), outer, True)
                        if maker.IsDone():
                            filled = maker.Face()
                            filled.Orientation(face.Orientation())
                            if BRepCheck_Analyzer(filled).IsValid():
                                face = filled
                try:
                    projected.extend(sweep(face, vector, reach))
                except (ShellError, RuntimeError):
                    repair = ShapeFix_Face(face)
                    repair.Perform()
                    projected.extend(sweep(repair.Face(), vector, reach))
            except (ShellError, RuntimeError) as error:
                raise ShellError(f"原生扫掠失败：零件 {part_index}、面 {face_index}、方向 {opening.label}。{error}") from error
        layered = fused(projected, f"零件 {part_index} 的扫掠合并")
        swept.extend(solids(operate(BRepAlgoAPI_Common, [layered], [trim], "包络预裁切"),
                            f"零件 {part_index} 的外包络"))
    return swept


def offset_union(items, distance):
    shifted = []
    for index, item in enumerate(items, 1):
        try:
            shifted.append(offset(item, distance))
        except (ShellError, RuntimeError) as error:
            raise ShellError(f"包络实体 {index} 的 {distance:g} mm CAD 偏移失败。{error}") from error
    return fused(shifted, "重叠偏移区域合并")


def forming(inner, opening):
    shells = []
    builder = BRep_Builder()
    for solid in solids(inner, "内包络"):
        sheet = TopoDS_Shell()
        builder.MakeShell(sheet)
        cap_count = 0
        for item in members(solid, TopAbs_FACE):
            if is_trim(BRepAdaptor_Surface(TopoDS.Face_s(item)), opening):
                cap_count += 1
            else:
                builder.Add(sheet, item)
        if not cap_count or BRep_Tool.IsClosed_s(sheet) or not BRepCheck_Analyzer(sheet).IsValid():
            raise ShellError("成型曲面没有有效开口，请调整开口内移量。")
        shells.append(sheet)
    return compound(shells)


@dataclass
class NativeResult:
    surface: object
    shell: object
    solid: object
    opening: Opening
    gap: float
    wall: float
    _exports: dict = field(default_factory=dict)

    def info(self):
        return "原生 CAD 外包络"

    def notice(self):
        return ""

    def step(self, kind):
        if kind not in ("surface", "shell", "solid") or getattr(self, kind) is None:
            raise ShellError("当前结果没有此导出类型。")
        if kind not in self._exports:
            shape = getattr(self, kind)
            data = step_bytes(shape)
            restored = read_step(data)
            if kind == "surface":
                before = members(shape, TopAbs_SHELL)
                after = members(restored, TopAbs_SHELL)
                if len(before) != len(after) or any(BRep_Tool.IsClosed_s(item) for item in after):
                    raise ShellError("成型曲面回读后的开口拓扑有误。")
            else:
                before = solids(shape, "输出")
                after = solids(restored, "STEP 回读")
                if len(before) != len(after):
                    raise ShellError("STEP 回读的实体数量有误。")
                for precision in (1e-7, 1e-10):
                    original_volume = sum(volume(item, precision=precision) for item in before)
                    restored_volume = sum(volume(item, precision=precision) for item in after)
                    if abs(restored_volume-original_volume) <= max(1e-5, original_volume*1e-6):
                        break
                else:
                    raise ShellError("STEP 回读的体积超出公差。")
            if not BRepCheck_Analyzer(restored).IsValid():
                raise ShellError("STEP 回读几何无效。")
            self._exports[kind] = data
        return self._exports[kind]


def directional_result(shape, vector, label, depth, gap, wall, progress, convex=None):
    parts = members(shape, TopAbs_SOLID)
    if not parts or len(members(compound(parts), TopAbs_FACE)) != len(members(shape, TopAbs_FACE)):
        raise ShellError("STEP 需要闭合的 CAD 实体，检测到游离曲面或没有实体。")
    opening = plane_for_solid(shape, vector, label, depth)
    cutting = halfspace(vector, opening.height)
    # Keep the temporary sweep cap beyond the opening during both offsets.
    span = np.linalg.norm(np.ptp(bounds(shape), axis=0))
    extension = gap + wall + max(.05, span*.002)
    trim = halfspace(vector, opening.height + depth + extension)
    reach = span + extension*2
    try:
        if convex is None:
            layers = sweep_parts(parts, opening, reach, trim, progress)
            try:
                reference = solids(fused(layers, "装配外包络合并"), "装配外包络")
            except (ShellError, RuntimeError):
                reference = layers
        else:
            reference = layers = [convex]
        progress(.53, "等距偏移原生 CAD 曲面")
        try:
            inner = offset_union(reference, gap)
            outer = offset_union(reference, gap+wall) if wall else inner
        except (ShellError, RuntimeError):
            if len(layers) == len(reference):
                raise
            inner = offset_union(layers, gap)
            outer = offset_union(layers, gap+wall) if wall else inner
    except (ShellError, RuntimeError) as original:
        if convex is not None:
            raise
        # Dilation and directional sweep commute. For exterior faces with no
        # perforations, retry the offset before the sweep to avoid coincident
        # or very short edges where the original and swept surfaces meet.
        if any(len(members(face, TopAbs_WIRE)) != 1 for part in parts
               for face in members(exterior_solid(part), TopAbs_FACE)):
            raise
        progress(.56, "重试 CAD 偏移与扫掠")
        def offset_first(distance):
            moved = [offset(exterior_solid(item), distance) for item in parts]
            return fused(sweep_parts(moved, opening, reach, trim, lambda *_: None),
                         "外偏装配合并")
        try:
            inner = offset_first(gap)
            outer = offset_first(gap+wall) if wall else inner
        except (ShellError, RuntimeError) as error:
            raise ShellError(f"{original} 重试后仍未成功：{error}") from error
    progress(.80, "裁切壳口并检查拓扑")
    inner_cut = operate(BRepAlgoAPI_Common, [inner], [cutting], "内壁裁切")
    sheet = forming(inner_cut, opening)
    outer_cut = operate(BRepAlgoAPI_Common, [outer], [cutting], "外壁裁切") if wall else inner_cut
    solids(outer_cut, "外偏实心体")
    shell = None
    if wall:
        shell = smoothed(operate(BRepAlgoAPI_Cut, [outer_cut], [inner_cut], "壳体成型"))
        solids(shell, "壁厚壳体")
    progress(1., "原生 CAD 曲面已生成")
    return NativeResult(sheet, shell, outer_cut, opening, gap, wall)
