from pathlib import Path
from dataclasses import dataclass
import math
from model import inp

@dataclass
class Simulation:
    template:str='standard'
    turns:float=.25
    duration:float=1
    friction:float=.12
    preload:float=1000
    density:float=7.85e-9
    material:str='CARBON_STEEL'
    youngs:float=210000.
    poisson:float=.30
    def validate(self,p):
        if not p.nut:raise ValueError('仿真模板需要螺母；请在建模页勾选“生成螺母”并重新划分网格')
        if self.template not in ('standard','explicit','preload'):raise ValueError('未知仿真模板')
        if not all(math.isfinite(v) for v in (self.turns,self.duration,self.friction,self.preload,self.density,self.youngs,self.poisson)):raise ValueError('仿真参数需为有限数字')
        if self.duration<=0 or self.density<=0:raise ValueError('时间和密度必须大于零')
        if not 0<=self.friction<=1:raise ValueError('摩擦系数需在 0–1 之间')
        if self.preload<=0:raise ValueError('预紧力需大于零')
        if self.youngs<=0 or not (0<self.poisson<.5):raise ValueError('材料弹性参数无效')
        if self.template!='preload':
            final=p.nut_z-self.turns*p.pitch
            if self.turns<=0:raise ValueError('旋入圈数必须大于零')
            if p.segments:
                if final<p.washer_stack_height or not any(lo<=final<=hi and p.nut_z<=span.end
                    for (lo,hi),span in zip(p.thread_windows(nominal_only=True),p.thread_spans(nominal_only=True))):
                    raise ValueError('旋入路径须留在同一段螺纹内，并避开头下垫圈')
            elif final<max(p.full_thread_start,p.washer_stack_height):
                raise ValueError('旋入终点进入光杆/退刀区；减小圈数或增加 b、a')
        else:
            if p.segments:
                if not any(lo<=p.nut_z and p.nut_z+p.nut_height<=hi for lo,hi in p.thread_windows(nominal_only=True)):
                    raise ValueError('预紧模板需要螺母完全处于同一段完整螺纹内')
                p.pretension_diameter(p.partition_z)
            elif p.nut_z+p.nut_height>p.length-.4*p.pitch:
                raise ValueError('预紧模板需要螺母完全啮合，请减小 a')

def template(parts,p,s,out):
    s.validate(p);out=Path(out);out.mkdir(parents=True,exist_ok=True)
    by_name={part['name']:part for part in parts}
    if not {'bolt','nut'}.issubset(by_name):raise ValueError('仿真模板需要螺栓和螺母网格')
    # Washer contact and constraints are not yet part of these templates.
    analysis_parts=[by_name['bolt'],by_name['nut']]
    bolt_part,nut_part=analysis_parts
    if s.template=='preload' and not bolt_part['all_surfaces']['PRETENSION']:raise ValueError('请先生成带预紧截面分区的网格')
    if not nut_part['nsets']['DRIVE']:raise ValueError('未找到螺母外侧驱动节点')
    path=out/(s.template+'.inp');inp(analysis_parts,p,path);txt=path.read_text()
    assembly='*Node\n900000001, 0., 0., %.12g\n'%(p.nut_z+p.nut_height/2)
    if s.template=='preload':assembly+='900000002, 0., 0., %.12g\n'%p.partition_z
    assembly+='*Nset, nset=NUT_RP\n900000001\n'
    if s.template=='preload':assembly+='*Nset, nset=PRE_RP\n900000002\n'
    assembly+='*Surface, type=NODE, name=NUT_DRIVE_NODES\nNUT-1.DRIVE_NODES, 1.\n'
    assembly+='*Coupling, constraint name=NUT_DRIVE, ref node=NUT_RP, surface=NUT_DRIVE_NODES\n*Kinematic\n1, 6\n'
    # Drive only the outer wrench flats. Thread nodes remain deformable.
    if s.template=='preload':
        assembly+='*Pre-Tension Section, surface=BOLT-1.PRETENSION, node=PRE_RP\n0., 0., 1.\n'
    txt=txt.replace('*End Assembly',assembly+'*End Assembly')
    txt=txt.replace('*Solid Section, elset=SOLID, material=STEEL','*Solid Section, elset=SOLID, material='+s.material)
    txt=txt.replace('*Material, name=STEEL\n*Elastic\n210000., 0.3',f'*Material, name={s.material}\n*Density\n{s.density:.12g}\n*Elastic\n{s.youngs:.12g}, {s.poisson:.8g}')
    txt+='*Surface Interaction, name=THREAD_CONTACT\n*Surface Behavior, pressure-overclosure=HARD\n'
    txt+=f'*Friction\n{s.friction:.8g}\n'
    # Standard/Explicit general contact supports penalty with quadratic tetrahedra.
    contact='*Contact\n*Contact Inclusions\nBOLT-1.THREAD_SURFACE, NUT-1.THREAD_SURFACE\n*Contact Property Assignment\n, , THREAD_CONTACT\n'
    if s.template!='explicit':txt+=contact
    txt+='*Boundary\nBOLT-1.HEAD_BASE_NODES, 1, 3\nNUT_RP, 1, 2\nNUT_RP, 4, 5\n'
    if s.template=='preload':
        txt+='** Fixture idealization: nut wrench flats fixed axially; replace by clamped joint in production.\n*Boundary\nNUT_RP, 3, 3\nNUT_RP, 6, 6\n'
        txt+='*Step, name=PRELOAD, nlgeom=YES, inc=1000\n*Static\n0.01, 1., 1e-08, 0.1\n'
    elif s.template=='standard':
        txt+='*Amplitude, name=DRIVE_RAMP, definition=SMOOTH STEP\n0., 0., %.12g, 1.\n'%s.duration
        txt+='*Step, name=SCREW_IN, nlgeom=YES, inc=10000\n*Static\n%.12g, %.12g, %.12g, %.12g\n'%(s.duration*.002,s.duration,s.duration*1e-9,s.duration*.02)
    else:
        txt+='*Amplitude, name=DRIVE_RAMP, definition=SMOOTH STEP\n0., 0., %.12g, 1.\n'%s.duration
        txt+='*Step, name=SCREW_IN, nlgeom=YES\n*Dynamic, Explicit\n, %.12g\n*Bulk Viscosity\n0.06, 1.2\n'%s.duration
    if s.template=='explicit':txt+=contact
    if s.template=='preload':txt+='*Cload\nPRE_RP, 1, %.12g\n'%s.preload
    else:
        # Same amplitude enforces the exact screw relation at every increment.
        # Right hand helix z=P*theta/(2*pi); inward motion => both negative.
        txt+='*Boundary, amplitude=DRIVE_RAMP\nNUT_RP, 3, 3, %.12g\nNUT_RP, 6, 6, %.12g\n'%(-s.turns*p.pitch,-s.turns*2*math.pi)
    txt+='*Output, field, number interval=20\n*Node Output\nU, RF\n*Element Output\nS, LE\n*Contact Output\nCSTRESS, CDISP\n*Output, history, frequency=1\n*Node Output, nset=NUT_RP\nU3, UR3, RF3, RM3\n*Energy Output\nALLIE, ALLKE, ALLAE, ALLWK\n*End Step\n'
    if s.template=='preload':
        txt+='*Step, name=LOCK_LENGTH, nlgeom=YES\n*Static\n0.1, 1., 1e-08, 0.2\n*Cload, op=NEW\n*Boundary, fixed\nPRE_RP, 1, 1\n*End Step\n'
    path.write_text(txt,encoding='ascii')
    note='旋入模板：螺母外侧扳手面采用 RP 运动耦合，牙面保持可变形。U3=-nP，UR3=-2πn，两者使用相同平滑幅值；这属于强制螺旋路径，不是由接触自由求出的旋进量。\n'
    if s.template=='preload':note='预紧模板：共形光杆截面 + PRE-TENSION SECTION，先施加预紧力，再固定当前长度。头底面固定、螺母外侧面轴向固定为占位夹持；实际工程需替换为被连接件和承压接触。\n'
    note+='需用 Abaqus datacheck 检查，并完成实际求解及收敛验证；Explicit 准静态应检查 ALLKE/ALLIE、ALLAE/ALLIE，时间不宜仅为缩短计算而随意减小。没有自动质量缩放。\n'
    (out/(s.template+'_说明.txt')).write_text(note,encoding='utf-8')
    return path
