from cad_kernel import has_positive_volume, load as cadquery, volume, volume_change_between
from dataclasses import dataclass,asdict,replace
from pathlib import Path
import math,json,os,time,traceback
from collections import OrderedDict
from functools import lru_cache
from threading import RLock
from shank import Segment, Span, edge_breaks, resolve, runout
import numpy as np
from legacy_engine import threaded_solid,write_inp
from standards import washer_dimensions,FLAT_WASHERS
from nut_geometry import nut_chamfers, chamfered_nut_stock, nut_countersinks
from fastener_heads import PRODUCTS, DRIVE_HEADS, HEX_TYPES, SOCKET_HEADS, make_head, cut_socket, cut_slot, neck_reduction, socket_relief, threaded_tip, trim_threaded_end

class ModelError(RuntimeError):
    pass

WASHER_DIMS={d:washer_dimensions(d) for d in FLAT_WASHERS}

@dataclass
class Parameters:
    diameter:float=8
    pitch:float=1.25
    length:float=24
    thread_length:float=16
    nut_height:float=6.8
    head_type:str='socket'
    head_width:float=13
    head_height:float=8
    socket_width:float=6.020
    socket_depth:float=4
    nut_width:float=13
    assembly_distance:float=15.95
    clearance:float=.05
    root_radius:float=.10
    neck_radius:float=.4
    fine_size:float=.4375
    coarse_size:float=2.5
    root_size_ratio:float=1.8
    element:str='C3D10'
    curved:bool=False
    partition_z:float=4
    adaptive:bool=True
    mesh_algorithm:str='delaunay'
    washer:bool=False
    spring_washer:bool=False
    nut:bool=True
    segments:tuple[Segment, ...]=()
    chamfer_segments:bool=True

    def __post_init__(self):
        # Diagnose/snapshot data also round-trips through dataclasses.asdict.
        self.segments=tuple(Segment(**item) if isinstance(item,dict) else item for item in self.segments)
        if self.segments:
            shank=resolve(self.segments,self.diameter)
            self.length=shank[-1].end
            self.thread_length=math.fsum(s.length for s in shank if s.kind=='thread')

    def spans(self,merge=False):
        if self.segments:return resolve(self.segments,self.diameter,merge)
        boundary=self.length-self.thread_length
        thread=Span('thread',max(0,boundary),self.length,self.diameter)
        return (Span('plain',0.,boundary,self.diameter),thread) if boundary>0 else (thread,)

    @property
    def seat_diameter(self):
        return self.spans()[0].diameter

    def shank_edge_breaks(self, spans):
        if self.segments and self.chamfer_segments:
            return edge_breaks(spans,self.pitch,self.neck_radius)
        return ((0.,0.),)*len(spans)

    def thread_spans(self, *, nominal_only=False):
        return tuple(span for span in self.spans(merge=True) if span.kind=='thread'
                     and (not nominal_only or abs(span.diameter-self.diameter)<1e-8))

    def thread_windows(self, *, nominal_only=False):
        if not self.segments:return ((self.full_thread_start,self.length-.6*self.pitch),)
        windows=[]
        terminal=self.spans(merge=True)[-1]
        for span in self.thread_spans(nominal_only=nominal_only):
            lead,exit=runout(span,self.pitch,self.neck_radius)
            if span==terminal:
                exit=max(exit,threaded_tip(self,span)[0])
            windows.append((span.start+lead,span.end-exit))
        return tuple(windows)

    def pretension_diameter(self,z):
        if not self.segments:
            if max(self.neck_radius,self.pitch*.2)<z<self.length-self.thread_length-self.pitch*.6:return self.diameter
        else:
            spans=self.spans(merge=True)
            for span,(lead,exit) in zip(spans,self.shank_edge_breaks(spans)):
                margin=max(.01,min(.15*self.pitch,.15*span.length))
                low=span.start+max(lead,self.neck_radius if span.start==0 else 0.)+margin
                if span.kind=='plain' and low<z<span.end-exit-margin:return span.diameter
        raise ValueError('预紧截面必须位于光杆内部，并避开头杆圆角和轴肩')

    def mesh_key(self, *, use_partition=True):
        return (self.fine_size,self.coarse_size,self.root_size_ratio,self.element,
                self.curved,self.partition_z if use_partition else None,self.adaptive,self.mesh_algorithm)

    def geometry_key(self):
        values=asdict(self)
        for key in ('fine_size','coarse_size','root_size_ratio','element','curved','partition_z','adaptive','mesh_algorithm'):
            values.pop(key)
        values['segments']=self.spans(merge=True) if self.segments else ()
        return tuple(values.items())

    @property
    def nut_z(self):return self.assembly_distance
    @property
    def thread_start(self):
        if self.segments:return next((s.start for s in self.spans() if s.kind=='thread'),self.length)
        # Engineering runout: reserve a neck for the fillet, then fade the
        # grooves into a full-diameter shank over one pitch. b remains nominal.
        return max(self.length-self.thread_length,self.neck_radius+.2*self.pitch)
    @property
    def full_thread_start(self):
        if self.segments:return next((a for a,b in self.thread_windows()),self.length)
        return self.thread_start+self.pitch
    @property
    def washer_seat(self):
        if not (self.washer or self.spring_washer) or not self.neck_radius:return 0.
        fi,_,_,si,_,_=washer_dimensions(self.diameter)
        allowance=((si if self.spring_washer else fi)-self.seat_diameter)/2+neck_reduction(self)
        rn=self.neck_radius
        # A sharp nominal bore may sit on the fillet before reaching z=0.
        # Retain the standard dimensions instead of silently opening the bore.
        return rn-math.sqrt(max(0,rn*rn-max(0,rn-allowance)**2)) if allowance<rn else 0.
    @property
    def washer_stack_height(self):
        if not (self.washer or self.spring_washer):return 0.
        _,_,ft,_,_,st=washer_dimensions(self.diameter)
        return self.washer_seat+(ft if self.washer else 0.)+(st if self.spring_washer else 0.)
    def validate(self):
        errs=[]
        for k,v in asdict(self).items():
            if isinstance(v,(int,float)) and not math.isfinite(v):errs.append(k+' 必须是有限数字')
        d,P,L,b=self.diameter,self.pitch,self.length,self.thread_length
        if not (2<=d<=64):errs.append('公称直径 d 应为 2–64 mm')
        if not (.15<=P<=d*.35):errs.append('螺距 P 应在 0.15–0.35d 之间')
        if not self.segments and not (2*P<=b<=L):errs.append('螺纹长度 b 需满足 2P ≤ b ≤ L')
        if not (0<L<=20*d):errs.append('杆长 L 需为正且 ≤20d')
        if self.nut and self.nut_height<1.5*P:errs.append('螺母高度 m 至少为 1.5P')
        if self.head_type not in PRODUCTS and self.head_type not in HEX_TYPES:errs.append('未知头型')
        if self.head_type in DRIVE_HEADS and self.head_type!='socket' and d not in DRIVE_HEADS[self.head_type]:
            errs.append('当前头型仅支持尺寸表中列出的公称规格')
        if self.head_type=='countersunk':
            if self.washer or self.spring_washer:errs.append('沉头锥面请使用沉孔，以匹配锥面承压')
            if self.head_width/2-self.seat_diameter/2-self.neck_radius >= self.head_height:
                errs.append('沉头的 90° 锥面超出头高，请核对头径、头高与首段直径')
        if self.head_width<=self.seat_diameter+2*self.neck_radius:errs.append('头部宽度不足以容纳杆径及头杆圆角')
        if self.head_height<=0:errs.append('头高 k 必须大于 0')
        if self.head_type in SOCKET_HEADS:
            if not (0<self.socket_width<self.head_width*.75):errs.append('内六角对边必须为正，且小于 0.75 倍头径')
            if not (0<self.socket_depth<self.head_height*.85):errs.append('内六角深度必须为正，且小于 0.85 倍头高')
        if self.head_type=='slotted':
            spec=DRIVE_HEADS['slotted'].get(d)
            if not (0<self.socket_width<self.head_width):errs.append('槽宽 n 必须小于头径')
            if spec and not (0<self.socket_depth<=self.head_height-spec.floor_min):
                errs.append('槽深 t 须保留足够的槽底厚度')
        if self.nut and self.nut_width<=d+2*self.clearance+.3*P:errs.append('螺母对边太小，孔与外壁间没有足够厚度')
        if self.nut and self.assembly_distance<0:errs.append('装配距离 a 不能小于 0')
        if not (0.002*P<=self.clearance<=.15*P):errs.append('径向间隙建议范围为 0.002P–0.15P')
        if not (.01*P<=self.root_radius<=.12*P):errs.append('牙根圆角 R 应在 0.01P–0.12P 之间')
        if not (0<=self.neck_radius<min(self.head_height*.5,P)):errs.append('头杆过渡圆角需小于头高的一半和一个螺距')
        if self.segments:
            spans=self.spans(merge=True)
            if spans[0].length<=self.neck_radius+.01:
                errs.append('头下首段太短，无法容纳头杆圆角')
            for i,span in enumerate(spans,1):
                if span.kind=='thread':
                    lead,exit=runout(span,P,self.neck_radius)
                    if i==len(spans):
                        exit=max(exit,threaded_tip(self,span)[0])
                    if not .15<=P<=.35*span.diameter:
                        errs.append(f'第 {i} 个有效分段的螺距 P 须在 0.15 mm 至本段直径的 0.35 倍之间')
                    if span.length-lead-exit<P-1e-8:
                        errs.append(f'合并连续同规格段后的第 {i} 段须为两端过渡留量，并保留至少一圈完整螺纹')
            if self.nut and not b:
                errs.append('全光杆模式请关闭“生成螺母”')
            elif self.nut and any(abs(s.diameter-d)>1e-8 for s in self.thread_spans()) and not any(
                    s.start<self.nut_z+self.nut_height and s.end>self.nut_z
                    for s in self.thread_spans(nominal_only=True)):
                errs.append('螺母须与上方 M 规格的螺纹段重叠，请调整装配距离 a 或关闭螺母')
        elif self.full_thread_start+P>L:errs.append('杆长不足以容纳头下圆角、收尾区和至少一圈完整螺纹')
        if self.washer or self.spring_washer:
            try:
                stack=self.washer_stack_height
                if stack>=L-.6*P:errs.append('垫圈总高已占满可用杆长，请增加杆长')
                if self.nut and self.nut_z<stack:errs.append('螺母与头下垫圈相交，请增加装配距离 a')
            except ValueError as ex:errs.append(str(ex))
        if not (.08*P<=self.fine_size<=P):errs.append('牙面网格尺寸 h 应在 0.08P–P 之间')
        if not (self.fine_size<=self.coarse_size<=d):errs.append('内部网格 H 应满足 h ≤ H ≤ d')
        if not .5<=self.root_size_ratio<=4:errs.append('牙根尺寸系数应在 0.5–4 之间（h根=系数×R）')
        if self.mesh_algorithm not in ('delaunay','hxt'):errs.append('未知体网格算法')
        if self.element not in ('C3D10','C3D10M'):errs.append('未知单元类型')
        if errs:raise ValueError('\n'.join(errs))
        w=[]
        windows=self.thread_windows(nominal_only=True)
        engaged=max((max(0,min(hi,self.nut_z+self.nut_height)-max(lo,self.nut_z)) for lo,hi in windows),default=0.)
        if self.nut and engaged<2*P:w.append('初始完整螺纹啮合不足 2 圈；旋入仿真需检查接触建立')
        if self.nut and not any(lo<=self.nut_z<=hi for lo,hi in windows):w.append('螺母入口未处于完整螺纹段，生成时会检查装配干涉')
        if self.fine_size>3*self.root_radius:w.append('牙面尺寸大于 3 倍牙根圆角；牙根应力建议进一步加密')
        if self.curved:w.append('曲边二次网格会检查雅可比；失败时不会静默改为直边')
        return w

def checked(stage,fn):
    try:
        shape=fn()
        if not shape.isValid() or len(shape.Solids())!=1 or not has_positive_volume(shape):raise ValueError('实体无效、体积为零或存在多个不连通实体')
        return shape
    except Exception as ex:
        advice={'螺纹':'螺纹生成未通过实体检查，详细原因和当前尺寸见下方日志。',
                '头杆圆角':'减小头杆圆角，确认有足够光杆及承压台阶。',
                '内六角':'减小内六角深度/对边，增加头高/头径。',
                '螺母':'检查螺母壁厚、间隙和装配位置。'}
        tip=next((v for k,v in advice.items() if k in stage),'请检查相交实体和尺寸比例。')
        raise ModelError(f'[{stage}] {type(ex).__name__}: {ex}\n建议：{tip}') from ex

_ASSEMBLY_CACHE=OrderedDict()
_ASSEMBLY_LOCK=RLock()


def geometry(p,log=print):
    p.validate()
    key=p.geometry_key()
    with _ASSEMBLY_LOCK:
        if key in _ASSEMBLY_CACHE:
            _ASSEMBLY_CACHE.move_to_end(key)
            log('复用已验证的整套 CAD 实体')
            return _ASSEMBLY_CACHE[key]
        result=_geometry(p,log)
        _ASSEMBLY_CACHE[key]=result
        if len(_ASSEMBLY_CACHE)>2:_ASSEMBLY_CACHE.popitem(last=False)
        return result


def _build_bolt_stock(p,log):
    cq=cadquery()
    r=p.diameter/2;start=p.thread_start
    phase_start=(start+.25*p.pitch if p.length-p.thread_length>p.neck_radius+.2*p.pitch else max(.05*p.pitch,start-.5*p.pitch));phase_angle=17.
    log('@progress:10')
    if p.segments:
        from segmented_cad import make_segmented_bolt
        bolt=make_segmented_bolt(p,cq,checked,threaded_solid,log)
        phase_start,phase_angle=0.,17.
    else:
        log('构建螺栓真实螺纹与牙根圆角…')
        log(f'头下颈部 {start:g} mm，螺纹渐变收尾至 z={p.full_thread_start:g} mm')
        profile=cq.Workplane('XZ').moveTo(0,0)
        if p.neck_radius>1e-6:
            rn=p.neck_radius
            relief=neck_reduction(p)
            fillet_radius=r-relief
            profile=(profile.lineTo(fillet_radius+rn,0)
                     .threePointArc((fillet_radius+rn*(1-2**-.5),rn*(1-2**-.5)),(fillet_radius,rn)))
            if relief and rn+relief<start:profile=profile.lineTo(r,rn+relief)
        else:profile=profile.lineTo(r,0)
        transition=(profile.lineTo(r,start).lineTo(r-.62*p.pitch,start+p.pitch)
                    .lineTo(0,start+p.pitch).close().revolve().val())
        head=checked('头部成形',lambda:make_head(p,cq))
        transition=transition.rotate((0,0,0),(0,0,1),phase_angle+17.)
        neck=checked('头杆圆角与坯体',lambda:head.fuse(transition).clean())
        # Offset the helix seam from the revolved neck seam. Coincident seams
        # otherwise cause OCC to occasionally omit faces while reporting validity.
        connected=None
        # Reposition the hidden endpoint inside the conical runout if its seam
        # prevents a valid union. Compensate rotation to preserve the global helix.
        starts=(phase_start,start+.25*p.pitch,start+.1*p.pitch,
                max(.025*p.pitch,phase_start-.75*p.pitch))
        # For long helical faces, coincident crest and neck surfaces can
        # make the first Boolean spend minutes at the underhead overlap.
        # Shorten the hidden overlap only where the neck covers the full crest.
        buried_start = start - .04*p.pitch
        if (p.length-phase_start >= 24*p.pitch and buried_start > phase_start
                and not neck_reduction(p)):
            starts = (buried_start,*starts)
        thread_error = None
        had_thread = False
        for candidate_start in dict.fromkeys(starts):
            candidate_angle = phase_angle+360*(candidate_start-phase_start)/p.pitch
            try:
                thread = checked('螺纹/螺栓', lambda:threaded_solid(
                    p.pitch,p.length-candidate_start,r,p.root_radius)).copy()
                thread = thread.rotate((0,0,0),(0,0,1),candidate_angle).translate((0,0,candidate_start))
            except ModelError as ex:
                thread_error = ex
                continue
            if not had_thread:
                log('@progress:40')
            had_thread = True
            try:
                merged=thread.fuse(neck).clean()
                if merged.isValid() and len(merged.Solids())==1 and volume_change_between(thread,merged,-1e-5) and volume_change_between(neck,merged,-1e-5):
                    connected=merged;phase_start=candidate_start;phase_angle=candidate_angle;break
            except Exception:pass
        if connected is None and not had_thread and thread_error is not None:
            raise thread_error
        if connected is None:raise ModelError(f'[螺纹收尾连接] 头下过渡区连接未通过检查；d={p.diameter:g}，P={p.pitch:g}，L={p.length:g}，b={p.thread_length:g}，Rn={p.neck_radius:g} mm。详细尺寸已保留在诊断记录中。')
        bolt=connected
    return bolt,phase_start,phase_angle


_BOLT_STOCK_CACHE=OrderedDict()


def _bolt_stock_key(p):
    return (p.diameter,p.pitch,p.length,p.thread_length,p.head_type,p.head_width,
            p.head_height,p.root_radius,p.neck_radius,
            p.spans(merge=True) if p.segments else (),p.chamfer_segments)


def _drive_end_z(p):
    if p.head_type in SOCKET_HEADS:
        _, lead, blind = socket_relief(p)
        return max(p.socket_depth+blind,lead+.015*p.socket_width)-p.head_height
    return p.socket_depth-p.head_height


def _build_bolt(p,log):
    cq=cadquery()
    has_drive = p.head_type in SOCKET_HEADS or p.head_type=='slotted'
    terminal = p.spans(merge=True)[-1]
    needs_tip = terminal.kind=='thread' and not p.segments
    separate_cuts = (has_drive and needs_tip and _drive_end_z(p) <
                     terminal.end-threaded_tip(p,terminal)[0]-1e-4)
    stock_key = _bolt_stock_key(p)
    if has_drive and stock_key in _BOLT_STOCK_CACHE:
        stock, tipped = _BOLT_STOCK_CACHE[stock_key]
        _BOLT_STOCK_CACHE.move_to_end(stock_key)
        log('复用已验证的头杆和螺纹坯体')
        log('@progress:45')
    else:
        stock, tipped = _build_bolt_stock(p,log), None
    bolt,phase_start,phase_angle = stock
    # Distinct cutters commute. Cache the preformed tail so drive edits only
    # rerun the head Boolean. Retain the old sequence as a recovery route.
    if separate_cuts and tipped is None:
        try:
            tipped = checked('螺栓末端成形',lambda:trim_threaded_end(p,bolt.copy(),terminal,cq))
        except ModelError:
            separate_cuts = False
    if has_drive:
        _BOLT_STOCK_CACHE[stock_key] = (stock,tipped)
        if len(_BOLT_STOCK_CACHE)>2:
            _BOLT_STOCK_CACHE.popitem(last=False)

    def drive(body):
        if p.head_type in SOCKET_HEADS:
            return checked('内六角孔与孔口倒角',lambda:cut_socket(p,body.copy(),cq))
        if p.head_type=='slotted':
            return checked('一字槽成形',lambda:cut_slot(p,body.copy(),cq))
        return body

    if separate_cuts:
        try:
            bolt=drive(tipped)
        except ModelError:
            separate_cuts=False
    if not separate_cuts:
        bolt=drive(stock[0])
        if needs_tip:
            bolt=checked('螺栓末端成形',lambda:trim_threaded_end(p,bolt,terminal,cq))
    if p.segments:
        from segmented_cad import retains_thread
        for span in p.thread_spans():
            if not retains_thread(bolt,span,p.pitch,p.neck_radius):
                raise ModelError(f'成形后 z={span.start:g}–{span.end:g} mm 的牙型检查未通过')
    return bolt,phase_start,phase_angle


_BOLT_CACHE=OrderedDict()
_BOLT_LOCK=RLock()


def _cached_bolt(p,log):
    key=(*_bolt_stock_key(p),p.socket_width,p.socket_depth)
    with _BOLT_LOCK:
        if key in _BOLT_CACHE:
            _BOLT_CACHE.move_to_end(key)
            log('复用已验证的螺栓实体')
            return _BOLT_CACHE[key]
        result=_build_bolt(p,log)
        # Avoid accumulating long helical B-Rep shapes during dimensional edits.
        _BOLT_CACHE[key]=result
        if len(_BOLT_CACHE)>3:_BOLT_CACHE.popitem(last=False)
        return result


@lru_cache(maxsize=4)
def _nut_local(diameter,pitch,width,height,clearance,root,angle,phase):
    """The same local part applies at axial positions spaced by a whole pitch."""
    cq=cadquery()
    radius=diameter/2+clearance
    cutter_z=-(1.+phase)*pitch
    cutter_length=math.ceil((height-cutter_z)/pitch+1.)*pitch
    cutter=(threaded_solid(pitch,cutter_length,radius,root).copy()
            .rotate((0,0,0),(0,0,1),angle).translate((0,0,cutter_z)))
    profile=nut_chamfers(diameter,pitch,width,height,clearance)
    stock=checked('螺母双面外倒角',lambda:chamfered_nut_stock(cq,height,profile))
    tapers=nut_countersinks(cq,height,profile)
    try:
        return checked('螺母螺纹和孔口倒角',lambda:stock.cut(cutter,*tapers).clean())
    except ModelError:
        # Keep the sequential construction for kernels that reject the combined cut.
        nut=checked('螺母内螺纹切除',lambda:stock.cut(cutter).clean())
        for taper in tapers:
            nut=checked('螺母孔口倒角',lambda: nut.cut(taper).clean())
        return nut


@lru_cache(maxsize=4)
def _nut_placed(diameter,pitch,width,height,clearance,root,angle,phase,z):
    return _nut_local(diameter,pitch,width,height,clearance,root,angle,phase).translate((0,0,z))


@lru_cache(maxsize=4)
def assembly_overlap(bolt,nut):
    from OCP.BRepExtrema import BRepExtrema_DistShapeShape

    # A positive gap rules out an intersection. Touching, near-touching,
    # and containment still use the exact volume check.
    try:
        distance=BRepExtrema_DistShapeShape()
        distance.LoadS1(bolt.wrapped)
        distance.LoadS2(nut.wrapped)
        if hasattr(distance,'SetMultiThread'):
            distance.SetMultiThread(True)
        distance.Perform()
        if distance.IsDone() and not distance.InnerSolution() and distance.Value()>1e-4:
            return 0.
    except RuntimeError:
        pass
    return volume(bolt.intersect(nut))


def _geometry(p,log):
    log("准备几何内核…")
    cq=cadquery()
    bolt,phase_start,phase_angle=_cached_bolt(p,log)
    log('@progress:55')
    nut=None
    if p.nut:
        log('构建同相位内螺纹螺母…')
        turns=(p.nut_z-phase_start)/p.pitch
        phase=round(turns-math.floor(turns),12)
        nut=_nut_placed(p.diameter,p.pitch,p.nut_width,p.nut_height,p.clearance,p.root_radius,
                        phase_angle%360.,phase,p.nut_z)
        overlap=assembly_overlap(bolt,nut)
        if overlap>1e-6 and overlap>volume(bolt)*1e-7:raise ModelError(f'[装配干涉] 螺栓与螺母重叠 {overlap:.5g} mm³；螺母可能进入头下收尾区，请增加装配距离 a 或检查间隙。')
    log('@progress:85')
    # z=0 is the head bearing face. Stack towards the bolt tip, independent
    # of the nut position: head -> spring washer -> flat washer.
    washer=spring_washer=None
    if p.washer or p.spring_washer:
        fi,fo,ft,si,so,st=washer_dimensions(p.diameter)
        def ring(ro,ri,h,z0):
            return cq.Solid.makeCylinder(ro,h,cq.Vector(0,0,z0)).cut(cq.Solid.makeCylinder(ri,h+.02,cq.Vector(0,0,z0-.01))).clean()
        if p.spring_washer:
            spring_washer=checked('压紧弹簧垫',lambda:compressed_spring_washer(si,so,st,p.washer_seat))
            log(f'头下弹垫（压紧态）：内径 {si:g}，外径 {so:g}，压紧厚度 {st:g} mm')
        if p.washer:
            wz=p.washer_seat+(st if p.spring_washer else 0.)
            washer=checked('平垫',lambda:ring(fo/2,fi/2,ft,wz))
            log(f'头下平垫 GB/T 97.1-2002：{fi:g}×{fo:g}×{ft:g} mm')
        if p.washer_seat>1e-6:log(f'垫圈保持标准孔径，按头杆圆角自动就位：距承压面 {p.washer_seat:.3g} mm')
        for name,shape in [('平垫',washer),('弹簧垫',spring_washer)]:
            if shape is None:continue
            if volume(bolt.intersect(shape))>max(1e-6,volume(shape)*1e-7):
                raise ModelError(f'[{name}装配] 垫圈孔与头杆圆角干涉，请减小头杆圆角 Rn。')
    log('@progress:92')
    return bolt,nut,washer,spring_washer


def compressed_spring_washer(inner,outer,thickness,z=0.):
    """Flattened split washer, nominal GB section retained.

    This is assembled CAD geometry. It does not encode the stresses resulting
    from compressing a free-state washer. A small angular split stays open so
    neither coincident end faces nor two disconnected solids are introduced.
    """
    cq=cadquery()
    ring=(cq.Workplane('XY').circle(outer/2).circle(inner/2)
          .extrude(thickness).val().translate((0,0,z)))
    extent=outer;gap=math.radians(5)
    slot=(cq.Workplane('XY').polyline([(0,0),(extent,-extent*math.tan(gap)),
                                      (extent,extent*math.tan(gap))]).close()
          .extrude(thickness+.02).val().translate((0,0,z-.01)))
    return ring.cut(slot).clean()

def export_step(shapes,out):
    cq=cadquery()
    out=Path(out);out.mkdir(parents=True,exist_ok=True)
    names=('bolt','nut','washer','spring_washer')
    actual=[(n,s) for n,s in zip(names,shapes) if s is not None]
    for n,s in actual:cq.exporters.export(s,str(out/(n+'.step')))
    cq.exporters.export(cq.Compound.makeCompound([s for _,s in actual]),str(out/'assembly.step'))

class MeshGenerationError(ModelError):
    pass


def mesh_part(name,p,shape,log=print,pretension=False):
    import gmsh
    def run(method):
        # Reset native option and meshing state between independent attempts.
        gmsh.initialize(readConfigFiles=False,interruptible=False)
        try:
            return _mesh_part(gmsh,name,p,shape,log,pretension,method)
        finally:
            gmsh.finalize()

    try:
        return run('cad')
    except MeshGenerationError as initial:
        reasons=[str(initial)]
        if 'periodic' in str(initial).lower() or pretension or p.curved:
            log('重建网格用周期面接缝，原始 CAD 保留。')
            try:
                return run('split')
            except Exception as exc:
                reasons.append(f'周期面分缝：{exc}')
        if not pretension and not p.curved:
            log('改用经闭合及体积检查的曲面生成直边二次体网格。')
            try:
                return run('skin')
            except Exception as exc:
                reasons.append(f'封闭曲面：{exc}')
        raise ModelError('['+name+' 体网格] '+ '\n'.join(reasons)) from initial


def _mesh_part(gmsh,name,p,shape,log,pretension,method):
    import tempfile
    from mesh_recovery import GROUPS,group_names,import_skin,remove_unused_faces,split_periodic_seams
    model=gmsh.model
    gmsh.option.setNumber('General.Terminal',0)
    gmsh.option.setNumber('General.NumThreads',max(1,min(4,os.cpu_count() or 1)))
    model.add(name)
    needs_thread=name=='nut' or (name=='bolt' and any(s.kind=='thread' for s in p.spans(merge=True)))
    root_curves=set()
    if method=='skin':
        volumes,labelled=import_skin(model,shape,name,p,log)
    else:
        # Use a BREP copy. Splits, when needed, exist only in the meshing model.
        fd,f=tempfile.mkstemp(suffix='.brep');os.close(fd)
        try:
            shape.exportBrep(f)
            model.occ.importShapes(f)
        finally:
            os.unlink(f)
        model.occ.synchronize()
        if method=='split':
            split_periodic_seams(model)
        if pretension and name=='bolt':
            z=p.partition_z
            at_cut=p.pretension_diameter(z)
            disk=model.occ.addDisk(0,0,z,at_cut,at_cut)
            model.occ.fragment(model.occ.getEntities(3),[(2,disk)])
            remove_unused_faces(model)
        volumes=model.getEntities(3)
        outer=set(model.getBoundary(volumes,combined=True,oriented=False))
        labelled={key:[] for key in GROUPS}
        for _,tag in sorted(outer):
            typ=model.getType(2,tag)
            bb=model.getBoundingBox(2,tag)
            center_z=model.occ.getCenterOfMass(2,tag)[2] if typ not in ('Plane','Cylinder','Cone','Torus') else 0.
            tags=group_names(name,p,typ,center_z,bb[2],bb[5])
            for key in tags:labelled[key].append(tag)
        if pretension and name=='bolt':
            candidates=set(model.getBoundary(volumes,combined=False,oriented=False))-outer
            tol=1e-5*p.diameter
            for _,tag in sorted(candidates):
                bb=model.getBoundingBox(2,tag)
                if abs(bb[2]-p.partition_z)<tol and abs(bb[5]-p.partition_z)<tol:
                    labelled['PRETENSION'].append(tag)
        bolt_threads=p.thread_spans() if name=='bolt' else ()
        edges={e for tag in labelled['THREAD_SURFACE'] for e in model.getBoundary([(2,tag)],oriented=False)}
        for d,tag in sorted(edges):
            box=model.getBoundingBox(d,tag)
            if box[5]-box[2]<=.4*p.pitch:continue
            lo,hi=model.getParametrizationBounds(d,tag)
            xyz=model.getValue(d,tag,[(lo[0]+hi[0])/2])
            rr=math.hypot(xyz[0],xyz[1])
            zz=xyz[2]
            local_d=next((s.diameter for s in bolt_threads if s.start-1e-7<=zz<=s.end+1e-7),None)
            if ((name=='bolt' and local_d is not None and rr<local_d/2-.40*p.pitch) or
                (name=='nut' and rr>p.diameter/2+p.clearance-.15*p.pitch)):
                root_curves.add(tag)
    thread=labelled['THREAD_SURFACE']
    if needs_thread and not thread:
        raise MeshGenerationError('没有找到螺纹曲面')
    for opt,val in [('Mesh.MeshSizeMin',min(p.fine_size*.5,p.root_radius*.9)),('Mesh.MeshSizeMax',p.coarse_size),('Mesh.MeshSizeFromPoints',0),('Mesh.MeshSizeFromCurvature',0),('Mesh.MeshSizeExtendFromBoundary',0),('Mesh.Algorithm',6),('Mesh.Algorithm3D',10 if p.mesh_algorithm=='hxt' else 1),('Mesh.OptimizeThreshold',.4)]:gmsh.option.setNumber(opt,val)
    fields=[]
    def distance_threshold(kind,tags,h,d0,d1):
        dist=gmsh.model.mesh.field.add('Distance');gmsh.model.mesh.field.setNumbers(dist,kind,tags);gmsh.model.mesh.field.setNumber(dist,'Sampling',120 if p.fine_size<=.30*p.pitch else 72)
        th=gmsh.model.mesh.field.add('Threshold')
        for k,v in [('InField',dist),('SizeMin',h),('SizeMax',p.coarse_size),('DistMin',d0),('DistMax',d1)]:gmsh.model.mesh.field.setNumber(th,k,v)
        fields.append(th)
    if thread and method!='skin':
        distance_threshold('SurfacesList',thread,p.fine_size,.10*p.pitch,1.4*p.pitch)
    # Refine helical edge neighbourhood; narrow band avoids refining the whole core.
    if root_curves:distance_threshold('CurvesList',sorted(root_curves),min(p.fine_size,p.root_size_ratio*p.root_radius),.2*p.root_radius,1.5*p.root_radius)
    if fields:
        mix=gmsh.model.mesh.field.add('Min');gmsh.model.mesh.field.setNumbers(mix,'FieldsList',fields);gmsh.model.mesh.field.setAsBackgroundMesh(mix)
    log(f'{name}: 牙面 h={p.fine_size:.4g}，根部≈{min(p.fine_size,p.root_size_ratio*p.root_radius):.4g}，内部 H={p.coarse_size:.4g} mm')
    log('体网格算法：'+('HXT' if p.mesh_algorithm=='hxt' else 'Delaunay'))
    retries=[]
    algorithms=(6,) if method=='skin' else ((6,5) if method=='cad' else (6,))
    for j,surface_algorithm in enumerate(algorithms):
        try:
            gmsh.option.setNumber('Mesh.Algorithm',surface_algorithm)
            gmsh.model.mesh.generate(3)
            counts=[sum(len(tags) for tags in gmsh.model.mesh.getElements(3,tag)[1]) for _,tag in volumes]
            if not counts or min(counts)<=0:
                raise RuntimeError('存在未生成网格的体域')
            break
        except Exception as exc:
            retries.append(f'二维算法 {surface_algorithm}: {exc}')
            # This error is emitted by Gmsh's shared periodic surface path.
            if 'periodic' in str(exc).lower() or j+1==len(algorithms):
                raise MeshGenerationError(' / '.join(retries)) from exc
            gmsh.model.mesh.clear()
            log('表面生成未完成，尝试另一种表面划分。')
    # Gmsh's native optimizer handles the narrow runout/fillet cells without
    # Netgen's Windows access violations at coincident CAD feature edges.
    difficult=p.curved or method!='cad' or p.fine_size<=.30*p.pitch
    gmsh.model.mesh.optimize('',niter=8 if difficult else 4)
    gmsh.model.mesh.optimize('Relocate3D',niter=5 if difficult else 2)
    gmsh.option.setNumber('Mesh.SecondOrderLinear',0 if p.curved else 1);gmsh.model.mesh.setOrder(2)
    # Avoid the unbounded high-order optimizer; validate projected midsides explicitly.
    tags,conn=gmsh.model.mesh.getElementsByType(11);con=np.asarray(conn,dtype=int).reshape(-1,10)[:,[0,1,2,3,4,5,6,7,9,8]]
    q=np.asarray(gmsh.model.mesh.getElementQualities(tags,'minSICN'));jac=np.asarray(gmsh.model.mesh.getElementQualities(tags,'minDetJac'))
    if not len(q) or not np.isfinite(q).all() or not len(jac) or not np.isfinite(jac).all() or jac.min()<=0 or q.min()<=0:raise MeshGenerationError('[网格雅可比] 发现倒置单元；建议减小 h、增大 R，或取消曲边模式。未发布 INP。')
    ns,xyz,_=gmsh.model.mesh.getNodes();xyz=np.asarray(xyz).reshape(-1,3)
    if method=='skin':
        order=np.argsort(ns)
        corner=xyz[order[np.searchsorted(ns[order],con[:,:4])]]
        edges=corner[:,1:]-corner[:,0,None]
        mass=abs(np.einsum('ij,ij->',edges[:,0],np.cross(edges[:,1],edges[:,2])))/6
        exact=shape.Volume()
        if abs(mass-exact)>max(1e-6,.0075*exact):
            raise MeshGenerationError('恢复后的体网格体积和 CAD 相差超过 0.75%')

    def facet_keys(tags):
        result=set()
        for t in tags:
            _,v=gmsh.model.mesh.getElementsByType(9,t)
            result.update(tuple(sorted(row[:3])) for row in np.asarray(v,dtype=int).reshape(-1,6))
        return result
    groups={key:facet_keys(tags) for key,tags in labelled.items()}
    from mesh_groups import assign_surfaces
    surfs,nsets=assign_surfaces(con,ns,xyz,groups,p.partition_z)
    if not surfs['THREAD_SURFACE'] and needs_thread:raise MeshGenerationError('[网格分组] 螺纹面为空')
    if pretension and name=='bolt' and not surfs['PRETENSION']:raise MeshGenerationError('[预紧截面] 未找到共形截面网格')
    # Only exterior surface triangles are materialized for compatibility.
    face_tags=sorted(t for _,t in outer) if method!='skin' else [t for _,t in model.getEntities(2)]
    tri=[]
    for tag in face_tags:
        _,cells=model.mesh.getElementsByType(9,tag)
        tri.extend(np.asarray(cells).reshape(-1,6)[:,:3].tolist())
    stat=dict(elements=len(con),nodes=len(ns),minSICN=float(q.min()),p01SICN=float(np.quantile(q,.01)),meanSICN=float(q.mean()),below_0_1=int((q<.1).sum()),minDetJac=float(jac.min()),curved=p.curved,thread_surface_faces=len(surfs['THREAD_SURFACE']),geometry_method=method)
    log(f"{name}: {len(con):,} 单元；min SICN={q.min():.3g}；1%分位={np.quantile(q,.01):.3g}")
    if q.min()<.02:log(f'{name}: 检出形状很差的单元，使用前请检查退刀区、过渡和网格收敛。')
    return dict(name=name,nodes=ns,xyz=xyz,conn=con,surfaces=surfs['THREAD_SURFACE'],thread_nodes=sorted(nsets['THREAD_SURFACE']),all_surfaces=surfs,nsets=nsets,stats=stat,triangles=tri)

def inp(parts,p,path):
    def write_rows(out, values):
        for start in range(0,len(values),16):
            out.write(', '.join(map(str,values[start:start+16]))+'\n')

    def write_surface(out, name, faces):
        if not faces:
            return
        sides={}
        for element,side in faces:
            sides.setdefault(side,[]).append(element)
        for side,elements in sides.items():
            out.write(f'*Elset, elset={name}_S{side}\n')
            write_rows(out,elements)
        out.write(f'*Surface, type=ELEMENT, name={name}\n')
        for side in sides:
            out.write(f'{name}_S{side}, S{side}\n')

    def write_sets(out, part):
        for name,values in part['nsets'].items():
            if values and name!='THREAD_SURFACE':
                out.write(f'*Nset, nset={name}_NODES\n')
                write_rows(out,sorted(values))
        for name,faces in part['all_surfaces'].items():
            if name!='THREAD_SURFACE':
                write_surface(out,name,faces)

    write_inp(parts,p,path,write_surfaces=write_surface,write_sets=write_sets)

def save_mesh(parts,p,out):
    out=Path(out);out.mkdir(parents=True,exist_ok=True)
    inp(parts,p,out/'assembly.inp')
    for part in parts:inp([part],p,out/(part['name']+'.inp'))
    (out/'parameters.json').write_text(json.dumps(asdict(p),ensure_ascii=False,indent=2),encoding='utf-8')
    (out/'quality.json').write_text(json.dumps({a['name']:a['stats'] for a in parts},ensure_ascii=False,indent=2),encoding='utf-8')
