"""GB/T 6170-2015 style 1 hex nut, double chamfer, without a washer face."""

from dataclasses import dataclass
from math import cos, pi, radians, tan


NUT_STANDARD = 'GB/T 6170-2015'

# Table 1 limits: da max, dw min, mw min (mm).
LIMITS = {
    2.5: (2.90, 4.10, 1.40), 3: (3.45, 4.60, 1.70),
    4: (4.60, 5.90, 2.30), 5: (5.75, 6.90, 3.50),
    6: (6.75, 8.90, 3.90), 8: (8.75, 11.60, 5.20),
    10: (10.80, 14.60, 6.40), 12: (13.00, 16.60, 8.30),
    16: (17.30, 22.50, 11.30), 20: (21.60, 27.70, 13.50),
    24: (25.90, 33.30, 16.20),
}


@dataclass(frozen=True)
class NutChamfers:
    bearing_radius: float
    corner_radius: float
    outside_depth: float
    mouth_radius: float
    bore_radius: float
    mouth_depth: float


def nut_chamfers(diameter, pitch, width, height, clearance):
    flat_radius = width / 2
    corner = flat_radius / cos(pi / 6)
    thread_radius = diameter / 2 + clearance
    root = thread_radius - .613434 * pitch
    mouth_limit, bearing_min, wrench_min = LIMITS.get(
        diameter, (diameter + .65*pitch, .9*width, .75*height))

    # Intersect a hexagon with a 20° cone measured from the end face.
    # Keep the standard's minimum flat height even at the hex vertices.
    slope = tan(radians(20))
    wrench_height = min(wrench_min, .84*height)
    max_depth = (height - wrench_height) / 2
    bearing = max((bearing_min + width) / 4, corner - max_depth/slope)
    if bearing >= flat_radius:
        # Non-standard combinations may be very thin relative to their width.
        bearing = min(bearing, corner - .02*height)

    # 120° included entry countersink. Keep material between the opening
    # and the outside edge, regardless of the user's custom thread clearance.
    bore = root - .005*pitch
    mouth = max(thread_radius, min((diameter + mouth_limit)/4,
                                   min(bearing, flat_radius) - .04*pitch))
    mouth_slope = tan(radians(60))
    mouth = min(mouth, bore + .4*height*mouth_slope)
    return NutChamfers(bearing, corner, (corner-bearing)*slope,
                       mouth, bore, (mouth-bore)/mouth_slope)


def chamfered_nut_stock(cq, height, profile):
    p = profile
    slope = tan(radians(20))
    extension = min(.01, (height/2-p.outside_depth)/(2*slope))
    outer = p.corner_radius + extension
    depth = p.outside_depth + extension*slope
    stock = cq.Workplane('XY').polygon(6, 2*p.corner_radius).extrude(height).val()
    envelope = (cq.Workplane('XZ').moveTo(0,0).lineTo(p.bearing_radius,0)
                .lineTo(outer,depth).lineTo(outer,height-depth)
                .lineTo(p.bearing_radius,height).lineTo(0,height).close().revolve().val())
    return stock.intersect(envelope).clean()


def nut_countersinks(cq, height, profile):
    p = profile
    return (cq.Solid.makeCone(p.mouth_radius,p.bore_radius,p.mouth_depth,cq.Vector()),
            cq.Solid.makeCone(p.bore_radius,p.mouth_radius,p.mouth_depth,
                              cq.Vector(0,0,height-p.mouth_depth)))
