"""STEP I/O, dimensions and offset helpers for the CAD envelope."""

from dataclasses import dataclass
from io import BytesIO
from math import isfinite
import os
from pathlib import Path
from tempfile import NamedTemporaryFile

import numpy as np

from OCP.Bnd import Bnd_Box
from OCP.BRep import BRep_Tool
from OCP.BRepAdaptor import BRepAdaptor_Surface
from OCP.BRepBndLib import BRepBndLib
from OCP.BRepCheck import BRepCheck_Analyzer
from OCP.BRepGProp import BRepGProp
from OCP.BRepOffsetAPI import BRepOffsetAPI_MakeOffsetShape
from OCP.GeomAbs import GeomAbs_Plane, GeomAbs_Sphere
from OCP.GProp import GProp_GProps
from OCP.IFSelect import IFSelect_RetDone
from OCP.STEPControl import STEPControl_AsIs, STEPControl_Reader, STEPControl_Writer
from OCP.TopAbs import TopAbs_FACE, TopAbs_SHELL, TopAbs_SOLID, TopAbs_VERTEX
from OCP.TopExp import TopExp
from OCP.TopTools import TopTools_IndexedMapOfShape
from OCP.TopoDS import TopoDS

TOL = 1e-6
DIRECTIONS = {
    "+X": (1, 0, 0), "-X": (-1, 0, 0),
    "+Y": (0, 1, 0), "-Y": (0, -1, 0),
    "+Z": (0, 0, 1), "-Z": (0, 0, -1),
}


class ShellError(ValueError):
    pass


def members(shape, kind):
    if shape.IsNull():
        return []
    mapping = TopTools_IndexedMapOfShape()
    TopExp.MapShapes_s(shape, kind, mapping)
    return [mapping.FindKey(i) for i in range(1, mapping.Extent()+1)]


def bounds(shape):
    bbox = Bnd_Box()
    BRepBndLib.AddOptimal_s(shape, bbox, False, False)
    return np.asarray(bbox.Get()).reshape(2, 3)


def volume(shape, *, precision=None):
    prop = GProp_GProps()
    if precision is not None:
        BRepGProp.VolumeProperties_s(shape, prop, precision, True)
    else:
        BRepGProp.VolumeProperties_s(shape, prop)
    return prop.Mass()


def read_step(source):
    reader = STEPControl_Reader()
    if isinstance(source, bytes):
        status = reader.ReadStream("input.step", BytesIO(source))
    else:
        path = Path(source).absolute()
        status = reader.ReadFile(os.fspath(path)) if os.name != "nt" or os.fspath(path).isascii() else (
            reader.ReadStream("input.step", BytesIO(path.read_bytes()))
        )
    if status != IFSelect_RetDone or reader.TransferRoots() != reader.NbRootsForTransfer():
        raise ShellError("STEP 读取失败，或部分装配项未能转换。")
    shape = reader.OneShape()
    if shape.IsNull():
        raise ShellError("STEP 没有可读取的几何。")
    return shape


def step_bytes(shape):
    writer, output = STEPControl_Writer(), BytesIO()
    if writer.Transfer(shape, STEPControl_AsIs) != IFSelect_RetDone or writer.WriteStream(output) != IFSelect_RetDone:
        raise ShellError("STEP 写入失败。")
    return output.getvalue()


def save_step(path, data, source=None):
    path = Path(path)
    if source and (path.resolve() == Path(source).resolve() or (path.exists() and path.samefile(source))):
        raise ShellError("请另存到其他文件名，避免覆盖原始 STEP。")
    if path.suffix.lower() not in {".step", ".stp"}:
        raise ShellError("输出文件请使用 .step 或 .stp 扩展名。")
    temporary = None
    try:
        with NamedTemporaryFile(dir=path.parent, suffix=".step", delete=False) as out:
            temporary = Path(out.name)
            out.write(data)
        os.replace(temporary, path)
    finally:
        if temporary is not None:
            temporary.unlink(missing_ok=True)


def boolean(kind, left, right):
    operation = kind(left, right)
    if not operation.IsDone() or operation.Shape().IsNull():
        raise ShellError("原始曲面布尔运算失败。")
    return operation.Shape()


def solid_only(shape, label):
    found = members(shape, TopAbs_SOLID)
    if (len(found) != 1 or len(members(shape, TopAbs_SHELL)) != 1 or
            len(members(shape, TopAbs_FACE)) != len(members(found[0], TopAbs_FACE)) or
            not BRepCheck_Analyzer(found[0]).IsValid() or volume(found[0]) <= 0):
        raise ShellError(f"{label}没有形成单个有效实体。")
    return TopoDS.Solid_s(found[0])


def offset(ref, distance):
    if distance == 0:
        return ref
    operation = BRepOffsetAPI_MakeOffsetShape()
    operation.PerformByJoin(ref, distance, TOL)
    if not operation.IsDone():
        raise ShellError(f"外表面偏移 {distance:g} mm 失败。")
    return solid_only(operation.Shape(), "偏移外包络")


@dataclass(frozen=True)
class Opening:
    normal: np.ndarray
    height: float
    label: str
    depth: float


def direction_vector(direction):
    try:
        if isinstance(direction, str):
            vector = np.asarray(DIRECTIONS[direction] if direction in DIRECTIONS else
                                [float(x) for x in direction.replace("，", ",").split(",")])
        else:
            vector = np.asarray(direction, dtype=float)
    except (ValueError, TypeError) as exc:
        raise ShellError("方向须为 ±X、±Y、±Z，或三个数值组成的向量。") from exc
    if vector.shape != (3,) or not np.isfinite(vector).all() or not np.any(vector):
        raise ShellError("请输入有效的非零三维开口方向。")
    vector = vector / np.max(abs(vector))
    vector = vector / np.linalg.norm(vector)
    label = next((key for key, axis in DIRECTIONS.items() if np.allclose(vector, axis, atol=1e-10)),
                 "(" + ", ".join(f"{x:.3g}" for x in vector) + ")")
    return vector, label


def is_trim(fit, opening):
    if fit.GetType() != GeomAbs_Plane:
        return False
    plane = fit.Plane()
    normal = np.array(plane.Axis().Direction().Coord())
    point = np.array(plane.Location().Coord())
    return (abs(normal @ opening.normal) > 1-1e-10 and
            abs(point @ opening.normal - opening.height) < 20*TOL)


def convex_reference(shape):
    parts = members(shape, TopAbs_SOLID)
    if len(parts) != 1 or len(members(shape,TopAbs_FACE)) != len(members(parts[0],TopAbs_FACE)):
        return None
    body = parts[0]
    if len(members(body, TopAbs_SHELL)) != 1 or not BRepCheck_Analyzer(body).IsValid():
        return None
    faces = [BRepAdaptor_Surface(TopoDS.Face_s(face)) for face in members(body, TopAbs_FACE)]
    if len(faces) == 1 and faces[0].GetType() == GeomAbs_Sphere:
        expected = 4*np.pi*faces[0].Sphere().Radius()**3/3
        return body if abs(volume(body)-expected) < expected*1e-7 else None
    if len(faces) > 96 or any(f.GetType()!=GeomAbs_Plane for f in faces):
        return None
    points = np.array([BRep_Tool.Pnt_s(TopoDS.Vertex_s(p)).Coord()
                       for p in members(body, TopAbs_VERTEX)])
    for f in faces:
        plane = f.Plane()
        signed=(points-np.asarray(plane.Location().Coord()))@np.asarray(plane.Axis().Direction().Coord())
        if signed.min() < -20*TOL and signed.max() > 20*TOL:
            return None
    return body


def plane_for_solid(reference, vector, label, depth):
    from OCP.BRepBuilderAPI import BRepBuilderAPI_Transform
    from OCP.gp import gp_Trsf
    x=np.cross(np.eye(3)[np.argmin(abs(vector))],vector)
    x/=np.linalg.norm(x)
    rotation=np.array((x,np.cross(vector,x),vector))
    t=gp_Trsf()
    t.SetValues(*np.column_stack((rotation,np.zeros(3))).ravel())
    lower, upper = bounds(BRepBuilderAPI_Transform(reference,t,False).Shape())[:,2]
    if depth >= upper-lower-20*TOL:
        raise ShellError("开口内移过大，截面已经到达外形另一侧。")
    return Opening(vector,float(upper-depth),label,depth)


def generate(shape, gap=.5, wall=3., end="+Y", progress=lambda *_: None, *, depth=0., resolution=0.):
    if not isfinite(gap) or not isfinite(wall) or gap < 0 or wall < 0:
        raise ShellError("避空间隙和壁厚须为非负数。")
    if not isfinite(depth) or depth < 0 or not isfinite(resolution) or resolution < 0:
        raise ShellError("开口内移量须为非负数。")
    from native_envelope import directional_result

    progress(.08, "识别外包络")
    vector, label = direction_vector(end)
    return directional_result(shape, vector, label, depth, gap, wall, progress,
                              convex=convex_reference(shape))

