"""Nominal engineering defaults; no dimensional tolerance certification."""
from fastener_heads import CROWN_TYPES, HEX_DETAILS, socket_dimensions

COMMON_LENGTHS=(6,8,10,12,16,20,25,30,35,40,45,50,55,60,65,70,80,90,100)
CAP_PARTIAL_FROM={2.5:25,3:25,4:30,5:30,6:35,8:40,10:45,12:55,16:65,20:80,24:90}

# d: P, external-hex s,k; socket head dk,k,s,t; nut s,m.
TABLE={
2.5:(.45,5,1.7,4.5,2.5,2,1.1,5,2),
3:(.5,5.5,2,5.5,3,2.5,1.3,5.5,2.4),
4:(.7,7,2.8,7,4,3,2,7,3.2),
5:(.8,8,3.5,8.5,5,4,2.5,8,4.7),
6:(1,10,4,10,6,5,3,10,5.2),
8:(1.25,13,5.3,13,8,6,4,13,6.8),
10:(1.5,16,6.4,16,10,8,5,16,8.4),
12:(1.75,18,7.5,18,12,10,6,18,10.8),
16:(2,24,10,24,16,14,8,24,14.8),
20:(2.5,30,12.5,30,20,17,10,30,18),
24:(3,36,15,36,24,19,12,36,21.5)}

# GB/T 97.1-2002, normal series, nominal bore / outside diameter / thickness.
FLAT_WASHERS={
    2.5:(2.7,6,.5),3:(3.2,7,.5),4:(4.3,9,.8),5:(5.3,10,1),
    6:(6.4,12,1.6),8:(8.4,16,1.6),10:(10.5,20,2),12:(13,24,2.5),
    16:(17,30,3),20:(21,37,3),24:(25,44,4)}
# GB/T 93-2025: minimum bore, square section h=n. The application shows
# an assembled, flattened washer of thickness h; free-state height is 2h–2.5h.
SPRING_WASHERS={
    2.5:(2.6,.65),3:(3.1,.8),4:(4.1,1.1),5:(5.1,1.3),
    6:(6.1,1.6),8:(8.1,2.1),10:(10.2,2.6),12:(12.2,3.1),
    16:(16.2,4.1),20:(20.2,5),24:(24.3,6)}

def washer_dimensions(d):
    if d not in FLAT_WASHERS:
        raise ValueError('垫圈国标尺寸表支持当前规格列表中的 M2.5–M24')
    fi,fo,ft=FLAT_WASHERS[d];si,st=SPRING_WASHERS[d]
    return fi,fo,ft,si,si+2*st,st

def defaults(d,head,L=None):
    if d not in TABLE: raise ValueError('自动尺寸表支持 M2.5–M24 列出的规格；其他规格请手动填写尺寸')
    P,s,k,dk,sk,ss,t,ns,m=TABLE[d]
    if L is None:
        L=min(COMMON_LENGTHS,key=lambda v:(abs(v-3*d),-v))
    profile=socket_dimensions(head,d)
    if profile is not None:
        dk,sk,ss,t=profile.diameter,profile.height,profile.across_flats,profile.depth
        partial_from=CAP_PARTIAL_FROM[d] if head=='socket' else (profile.thread_reference+5*P if profile.thread_reference else float('inf'))
        b=profile.thread_reference if L>=partial_from else L
        if head=='slotted':b=min(L,profile.thread_reference)
        rn=profile.fillet
        if head in CROWN_TYPES and b==L:
            rn=profile.full_fillet
    else:
        dk,sk=s,k
        b=L if head=='hex_full' else min(L,2*d+(6 if L<=125 else 12 if L<=200 else 25))
        rn=HEX_DETAILS[d][2]
    return dict(diameter=d,pitch=P,length=L,thread_length=b,nut_height=m,
                head_type=head,head_width=dk,head_height=sk,
                socket_width=ss,socket_depth=t,nut_width=ns,clearance=round(.04*P,4),
                root_radius=round(.08*P,4),neck_radius=rn,
                assembly_distance=max(0,round(L-m-P)),fine_size=round(.35*P,4),coarse_size=round(min(.4*d,2*P),4))
