from cad_kernel import has_positive_volume, load as cadquery, volume
"""Real helical metric thread geometry and Abaqus quadratic solid mesh."""
import json, math, time, os
from pathlib import Path
from dataclasses import dataclass, asdict
import numpy as np
from functools import lru_cache

@dataclass
class Parameters:
    diameter: float = 8
    pitch: float = 1.25
    length: float = 20
    thread_length: float = 10
    head_width: float = 13
    head_height: float = 5.3
    nut_width: float = 13
    nut_height: float = 6.5
    nut_z: float = 12
    clearance: float = .08
    root_radius: float = .08
    mesh_level: str = '均衡'
    element: str = 'C3D10'

    def validate(self):
        for k,v in asdict(self).items():
            if isinstance(v,(int,float)) and not math.isfinite(v): raise ValueError(f'{k}: 请输入有限数字')
        if not (2 <= self.diameter <= 64): raise ValueError('直径支持 2–64 mm')
        if not (.2 <= self.pitch <= self.diameter*.35): raise ValueError('螺距需在 0.2–0.35×直径之间')
        if not (self.pitch*2 <= self.thread_length <= self.length <= self.diameter*12): raise ValueError('需满足 2×螺距 ≤ 螺纹长 ≤ 杆长 ≤ 12×直径')
        if not (self.head_width>self.diameter and self.nut_width>self.diameter+2*self.clearance): raise ValueError('头部和螺母对边必须大于螺纹外径')
        if min(self.head_height,self.nut_height)<=self.pitch: raise ValueError('头高、螺母高需大于螺距')
        if not (self.length-self.thread_length <= self.nut_z and self.nut_z+self.nut_height <= self.length): raise ValueError('螺母必须完全处在有螺纹的杆段内')
        if not (0.005 <= self.clearance <= self.pitch*.15): raise ValueError('径向间隙需在 0.005–0.15×螺距之间')
        if not (.01*self.pitch <= self.root_radius <= .12*self.pitch): raise ValueError('牙根圆角需在 0.01–0.12×螺距之间')
        if self.mesh_level not in ('较少','均衡','精细') or self.element not in ('C3D10','C3D10M'): raise ValueError('未知网格选项')

@lru_cache(maxsize=6)
def threaded_solid(p, length, radius, root_fillet=0):
    cq=cadquery()
    if not all(math.isfinite(v) for v in (p,length,radius,root_fillet)):
        raise ValueError('螺纹尺寸必须为有限数字')
    if p<=0 or length<=0 or radius<=.613434*p or root_fillet<0:
        raise ValueError('螺距、长度、螺纹芯径必须为正，牙根圆角不能为负')
    turns=math.ceil(length/p-1e-9)
    blank=_thread_blank(p,turns,radius,root_fillet)
    if length >= turns*p-1e-7:
        return blank
    try:
        solid=blank.copy().intersect(cq.Solid.makeCylinder(radius+.1*p,length)).clean()
        return _finish_thread(solid,'最终长度截取',p,length,radius,root_fillet)
    except Exception as ex:
        raise RuntimeError(f'螺纹最终长度截取失败 · P={p:g} mm，长度={length:g} mm，直径={2*radius:g} mm：{ex}') from ex


def _finish_thread(shape, stage, pitch, length, radius, fillet):
    def valid(s):
        return s.isValid() and len(s.Solids())==1 and has_positive_volume(s)
    if valid(shape):
        return shape
    before=volume(shape)
    try:
        fixed=shape.fix()
        if valid(fixed) and abs(volume(fixed)-before)<=max(1e-7,abs(before)*1e-6):
            return fixed
    except Exception:
        pass
    raise RuntimeError(f'螺纹生成失败：{stage}；P={pitch:g} mm，长度={length:g} mm，直径={2*radius:g} mm，牙根R={fillet:g} mm。实体检查未通过，未输出模型。')


@lru_cache(maxsize=4)
def _thread_blank(p, turns, radius, root_fillet):
    cq=cadquery()
    length=turns*p
    root=radius-.613434*p
    def construct(stage,fn):
        try:
            return _finish_thread(fn(),stage,p,length,radius,root_fillet)
        except RuntimeError:
            raise
        except Exception as ex:
            raise RuntimeError(f'螺纹生成失败：{stage}；P={p:g} mm，长度={length:g} mm，直径={2*radius:g} mm。内核原因：{ex}') from ex
    helix=cq.Wire.makeHelix(p,length+2*p,root).translate((0,0,-p))
    profile=(cq.Workplane('XZ').moveTo(root-.035*p,-p-.4375*p)
             .lineTo(radius,-p-.0625*p).lineTo(radius,-p+.0625*p)
             .lineTo(root-.035*p,-p+.4375*p).close())
    ridge=construct('螺旋牙型扫掠',lambda:profile.sweep(helix,isFrenet=True).val())
    ridge=construct('牙型端部截取',lambda:ridge.intersect(cq.Solid.makeCylinder(radius+.1*p,length)))
    solid=construct('牙型与芯体连接',lambda:cq.Solid.makeCylinder(root,length).fuse(ridge).clean())
    if root_fillet:
        edges=[e for e in solid.Edges() if e.geomType()=='BSPLINE' and e.Length()>3*radius
               and abs(math.hypot(e.positionAt(.5).x,e.positionAt(.5).y)-root)<.005*p]
        if not edges:raise RuntimeError('螺纹生成失败：未识别到牙根圆角边')
        solid=construct('牙根圆角',lambda:solid.fillet(root_fillet,edges).clean())
    return solid

def make_geometry(p,out,log):
    cq=cadquery()
    log('生成真实右旋 60° 螺纹（OpenCASCADE）…')
    r=p.diameter/2; start=p.length-p.thread_length
    bolt=threaded_solid(p.pitch,p.thread_length,r,p.root_radius).translate((0,0,start))
    if start>1e-6:
        dz=min(start*.5,p.pitch*.5)
        stem=cq.Solid.makeCylinder(r,start-dz)
        transition=cq.Solid.makeCone(r,r-.60*p.pitch,2*dz,cq.Vector(0,0,start-dz))
        bolt=bolt.fuse(transition).fuse(stem).clean()
    head=cq.Workplane('XY').polygon(6,p.head_width*2/math.sqrt(3)).extrude(-p.head_height).val()
    bolt=bolt.fuse(head).clean()
    # Taper the last half pitch to eliminate partial-thread slivers at the tip.
    tip=p.pitch*.6
    envelope=cq.Solid.makeCylinder(p.head_width,p.length-tip+p.head_height,cq.Vector(0,0,-p.head_height))
    envelope=envelope.fuse(cq.Solid.makeCone(r+.01*p.pitch,r-.62*p.pitch,tip,cq.Vector(0,0,p.length-tip)))
    bolt=bolt.intersect(envelope).clean()
    # The nut cutter shares the same global helix phase as the bolt.
    cutter=threaded_solid(p.pitch,p.thread_length,r+p.clearance,p.root_radius).translate((0,0,start))
    nut=cq.Workplane('XY').polygon(6,p.nut_width*2/math.sqrt(3)).extrude(p.nut_height).val().translate((0,0,p.nut_z))
    nut=nut.cut(cutter).clean()
    chamfer=p.pitch*.5
    nut=nut.cut(cq.Solid.makeCone(r+p.clearance+chamfer,r+p.clearance-.62*p.pitch,chamfer,cq.Vector(0,0,p.nut_z))).clean()
    nut=nut.cut(cq.Solid.makeCone(r+p.clearance-.62*p.pitch,r+p.clearance+chamfer,chamfer,cq.Vector(0,0,p.nut_z+p.nut_height-chamfer))).clean()
    for name,shape in [('bolt',bolt),('nut',nut)]:
        if not shape.isValid() or len(shape.Solids())!=1: raise RuntimeError(name+f' 实体拓扑检查失败 valid={shape.isValid()} solids={len(shape.Solids())}')
        cq.exporters.export(shape,str(out/(name+'.step')))
    cq.exporters.export(cq.Compound.makeCompound([bolt,nut]),str(out/'assembly.step'))
    return bolt,nut

def mesh_part(name,p,out,log):
    import gmsh
    gmsh.initialize(interruptible=False)
    try:
        gmsh.option.setNumber('General.Terminal',0)
        gmsh.option.setNumber('General.NumThreads',min(4,os.cpu_count() or 1))
        gmsh.model.add(name)
        gmsh.model.occ.importShapes(str(out/(name+'.step')))
        gmsh.model.occ.synchronize()
        vols=gmsh.model.getEntities(3)
        if len(vols)!=1: raise RuntimeError(name+' STEP 回读不是单一实体')
        boundary=gmsh.model.getBoundary(vols,oriented=False)
        # Helical BSpline surfaces include flanks and rounded roots.
        thread_faces=[t for d,t in boundary if gmsh.model.getType(d,t) not in ('Plane','Cylinder','Cone')]
        if not thread_faces: raise RuntimeError('未检测到螺旋牙面')
        factor={'较少':.65,'均衡':.45,'精细':.30}[p.mesh_level]
        fine=p.pitch*factor; coarse=min(p.diameter*.35,p.pitch*2)
        gmsh.option.setNumber('Mesh.MeshSizeMin',fine*.45)
        gmsh.option.setNumber('Mesh.MeshSizeMax',coarse)
        gmsh.option.setNumber('Mesh.MeshSizeFromPoints',0)
        gmsh.option.setNumber('Mesh.MeshSizeFromCurvature',0)
        gmsh.option.setNumber('Mesh.MeshSizeExtendFromBoundary',0)
        dist=gmsh.model.mesh.field.add('Distance')
        gmsh.model.mesh.field.setNumbers(dist,'SurfacesList',thread_faces)
        gmsh.model.mesh.field.setNumber(dist,'Sampling',80)
        th=gmsh.model.mesh.field.add('Threshold')
        for k,v in [('InField',dist),('SizeMin',fine),('SizeMax',coarse),('DistMin',p.pitch*.3),('DistMax',p.pitch*2.5)]: gmsh.model.mesh.field.setNumber(th,k,v)
        gmsh.model.mesh.field.setAsBackgroundMesh(th)
        gmsh.option.setNumber('Mesh.Algorithm',6)
        gmsh.option.setNumber('Mesh.Algorithm3D',1)
        gmsh.option.setNumber('Mesh.OptimizeThreshold',.4)
        log(f'{name}: 局部尺寸 {fine:.3f} / 内部 {coarse:.3f} mm，生成网格…')
        gmsh.model.mesh.generate(3)
        gmsh.model.mesh.optimize('Netgen',niter=8)
        gmsh.model.mesh.optimize('Relocate3D',niter=5)
        # Straight midside nodes avoid inversion around small helical root radii.
        # Surface geometry converges with local h refinement; STEP stays exact.
        gmsh.option.setNumber('Mesh.SecondOrderLinear',1)
        gmsh.model.mesh.setOrder(2)
        tags,conn=gmsh.model.mesh.getElementsByType(11)
        if not len(tags): raise RuntimeError('没有生成十节点四面体')
        q=np.asarray(gmsh.model.mesh.getElementQualities(tags,'minSICN'))
        jac=np.asarray(gmsh.model.mesh.getElementQualities(tags,'minDetJac'))
        if not np.isfinite(q).all() or np.min(jac)<=0 or np.min(q)<=0: raise RuntimeError('出现负雅可比或无效单元，拒绝发布网格；请使用更细网格或调整圆角')
        nt,xyz,_=gmsh.model.mesh.getNodes(); xyz=np.asarray(xyz).reshape(-1,3)
        con=np.asarray(conn,dtype=int).reshape(-1,10)
        # Gmsh order 11: 12,23,31,14,34,24. Abaqus:12,23,31,14,24,34.
        con=con[:,[0,1,2,3,4,5,6,7,9,8]]
        surfaces={}; node_ids=set()
        for face in thread_faces:
            _,fc=gmsh.model.mesh.getElementsByType(9,face)
            for tri in np.asarray(fc,dtype=int).reshape(-1,6):
                surfaces[tuple(sorted(tri[:3]))]=True
                node_ids.update(map(int,tri))
        sf=[]
        for eid,e in enumerate(con,1):
            for side,idx in enumerate(((0,1,2),(0,3,1),(1,3,2),(2,3,0)),1):
                if tuple(sorted(e[list(idx)])) in surfaces: sf.append((eid,side))
        if not sf: raise RuntimeError('牙面接触分组为空')
        gmsh.write(str(out/(name+'.msh')))
        stat={'elements':len(tags),'nodes':len(nt),'minSICN':float(q.min()),'p01SICN':float(np.quantile(q,.01)),'meanSICN':float(q.mean()),'minDetJac':float(jac.min()),'below_0_1':int(np.sum(q<.1)),'thread_surface_faces':len(sf),'fine_size':fine,'coarse_size':coarse}
        log(f'{name}: {len(tags):,} 单元；最小质量 {q.min():.4f}')
        return dict(name=name,nodes=nt,xyz=xyz,conn=con,surfaces=sf,thread_nodes=sorted(node_ids),stats=stat)
    finally: gmsh.finalize()

def write_inp(parts,p,path, *, write_surfaces=None, write_sets=None):
    with open(path,'w',encoding='ascii') as f:
        f.write('*Heading\nBoltStudio - mm, N, MPa; real helical thread; geometry/mesh only\n')
        for part in parts:
            name=part['name'].upper()
            f.write(f'*Part, name={name}\n*Node\n')
            for n,xyz in zip(part['nodes'],part['xyz']): f.write(f'{n}, '+', '.join(f'{v:.12g}' for v in xyz)+'\n')
            f.write(f'*Element, type={p.element}, elset=SOLID\n')
            for i,e in enumerate(part['conn'],1): f.write(f'{i}, '+', '.join(map(str,e))+'\n')
            if part.get('thread_nodes'):
                f.write('*Nset, nset=THREAD_NODES\n')
                ns=part['thread_nodes']
                for i in range(0,len(ns),16): f.write(', '.join(map(str,ns[i:i+16]))+'\n')
            if write_surfaces is not None:
                write_surfaces(f,'THREAD_SURFACE',part.get('surfaces',()))
            elif part.get('surfaces'):
                f.write('*Surface, type=ELEMENT, name=THREAD_SURFACE\n')
                for eid,side in part['surfaces']: f.write(f'{eid}, S{side}\n')
            f.write('*Solid Section, elset=SOLID, material=STEEL\n,\n')
            if write_sets is not None:
                write_sets(f,part)
            f.write('*End Part\n')
        f.write('*Assembly, name=ASSEMBLY\n')
        for part in parts:
            n=part['name'].upper(); f.write(f'*Instance, name={n}-1, part={n}\n*End Instance\n')
        f.write('*End Assembly\n*Material, name=STEEL\n*Elastic\n210000., 0.3\n')

def preview(shapes,out):
    import matplotlib
    matplotlib.use('Agg')
    import matplotlib.pyplot as plt
    from mpl_toolkits.mplot3d.art3d import Poly3DCollection
    fig=plt.figure(figsize=(8,6),facecolor='#f5f7fb'); ax=fig.add_subplot(projection='3d')
    for shape,color in zip(shapes,['#8cafd0','#dbb16c']):
        vs,fs=shape.tessellate(.15,.12); vv=np.array([v.toTuple() for v in vs]); faces=vv[np.array(fs)]
        ax.add_collection3d(Poly3DCollection(faces,facecolor=color,edgecolor='none',alpha=1))
        ax.auto_scale_xyz(vv[:,0],vv[:,1],vv[:,2])
    bb=shapes[0].BoundingBox(); r=max(bb.xlen,bb.ylen)/2
    ax.set_xlim(-r*1.2,r*1.2); ax.set_ylim(-r*1.2,r*1.2); ax.set_zlim(bb.zmin,bb.zmax)
    ax.set_box_aspect((r*2,r*2,bb.zlen)); ax.view_init(20,35)
    ax.set_axis_off(); fig.tight_layout(); fig.savefig(out/'preview.png',dpi=140); plt.close(fig)

def generate(p,folder,log=print):
    p.validate(); out=Path(folder); out.mkdir(parents=True,exist_ok=True)
    if any(out.iterdir()): raise ValueError('输出目录非空，请选择新的项目文件夹')
    t=time.time()
    (out/'parameters.json').write_text(json.dumps(asdict(p),ensure_ascii=False,indent=2),encoding='utf-8')
    shapes=make_geometry(p,out,log); preview(shapes,out)
    parts=[mesh_part(n,p,out,log) for n in ('bolt','nut')]
    write_inp(parts,p,out/'assembly.inp')
    for part in parts: write_inp([part],p,out/(part['name']+'.inp'))
    report={'parameters':asdict(p),'quality':{part['name']:part['stats'] for part in parts},'seconds':round(time.time()-t,1),'geometry':'60 degree right-hand single-start nominal profile, rounded roots; radial clearance, no ISO tolerance-class certification','status':'positive sampled Jacobians; import and mesh convergence still required'}
    (out/'quality.json').write_text(json.dumps(report,ensure_ascii=False,indent=2),encoding='utf-8')
    (out/'import_abaqus.py').write_text("from abaqus import mdb\nimport os\nbase=os.path.dirname(os.path.abspath(__file__))\nm=mdb.ModelFromInputFile(name='BoltStudio',inputFileName=os.path.join(base,'assembly.inp'))\nmdb.saveAs(pathName=os.path.join(base,'assembly.cae'))\n",encoding='ascii')
    log(f'完成，用时 {time.time()-t:.1f} 秒。STEP、INP、MSH 和质量报告已输出。')
    return report

if __name__=='__main__':
    import argparse
    a=argparse.ArgumentParser(); a.add_argument('folder'); a.add_argument('--params'); args=a.parse_args()
    p=Parameters(**json.loads(Path(args.params).read_text(encoding='utf-8'))) if args.params else Parameters()
    generate(p,args.folder,lambda s: print(s,flush=True))
