"""Head geometry and dimensional limits for the stocked metric sizes."""
from dataclasses import dataclass, replace
from math import cos, pi, sqrt, tan

from cad_kernel import volume_change_between


@dataclass(frozen=True)
class SocketHead:
    diameter: float
    height: float
    across_flats: float
    depth: float
    fillet: float
    transition_max: float
    bearing_min: float
    floor_min: float
    thread_reference: float
    crown: float = 0.
    flat_reference: float = 0.
    edge_max: float = 0.
    full_fillet: float = 0.


# GB/T 70.1-2008, Table 1. Plain head dk max, k max, s min, t min, r min,
# da max, dw min, w min, b reference and v max.
CAP_HEADS = {
    2.5: SocketHead(4.5, 2.5, 2.020, 1.1, .1, 3.1, 4.18, .85, 17, edge_max=.25),
    3: SocketHead(5.5, 3, 2.520, 1.3, .1, 3.6, 5.07, 1.15, 18, edge_max=.3),
    4: SocketHead(7, 4, 3.020, 2, .2, 4.7, 6.53, 1.4, 20, edge_max=.4),
    5: SocketHead(8.5, 5, 4.020, 2.5, .2, 5.7, 8.03, 1.9, 22, edge_max=.5),
    6: SocketHead(10, 6, 5.020, 3, .25, 6.8, 9.38, 2.3, 24, edge_max=.6),
    8: SocketHead(13, 8, 6.020, 4, .4, 9.2, 12.33, 3.3, 28, edge_max=.8),
    10: SocketHead(16, 10, 8.025, 5, .4, 11.2, 15.33, 4, 32, edge_max=1),
    12: SocketHead(18, 12, 10.025, 6, .6, 13.7, 17.23, 4.8, 36, edge_max=1.2),
    16: SocketHead(24, 16, 14.032, 8, .6, 17.7, 23.17, 6.8, 44, edge_max=1.6),
    20: SocketHead(30, 20, 17.050, 10, .8, 22.4, 28.87, 8.6, 52, edge_max=2),
    24: SocketHead(36, 24, 19.065, 12, .8, 26.4, 34.81, 10.4, 60, edge_max=2.4),
}

# GB/T 70.2-2025 / ISO 7380-1:2022, Table 1. Select a crown radius
# within rf limits and a socket width/depth within the specified limits.
BUTTON_HEADS = {
    3: SocketHead(5.7, 1.65, 2.020, 1.04, .1, 3.6, 4.97, .20, 12, 3.5, 2.6, full_fillet=.30),
    4: SocketHead(7.6, 2.2, 2.520, 1.30, .2, 4.7, 6.66, .30, 14, 4.4, 3.8, full_fillet=.40),
    5: SocketHead(9.5, 2.75, 3.020, 1.56, .2, 5.7, 8.41, .38, 16, 5.5, 5, full_fillet=.45),
    6: SocketHead(10.5, 3.3, 4.020, 2.08, .25, 6.8, 9.26, .74, 18, 5.9, 6, full_fillet=.50),
    8: SocketHead(14, 4.4, 5.020, 2.60, .4, 9.2, 12.48, 1.05, 22, 7.7, 7.7, full_fillet=.70),
    10: SocketHead(17.5, 5.5, 6.020, 3.12, .4, 11.2, 15.70, 1.45, 26, 9.5, 10, full_fillet=.70),
    12: SocketHead(21, 6.6, 8.025, 4.16, .6, 13.7, 18.84, 1.63, 30, 10.85, 12, full_fillet=1.10),
    16: SocketHead(28, 8.8, 10.025, 5.20, .6, 17.7, 25.28, 2.25, 48, 14.9, 16, full_fillet=1.10),
}

# GB/T 70.3-2023: actual dk max, reference k max, s min, t min, r min, b.
COUNTERSUNK_HEADS = {
    2.5: SocketHead(5.08, 1.69, 1.520, 1.00, .1, 0, 0, 0, 0),
    3: SocketHead(5.81, 1.86, 2.020, 1.10, .1, 0, 0, 0, 18),
    4: SocketHead(7.96, 2.48, 2.520, 1.40, .2, 0, 0, 0, 20),
    5: SocketHead(10.07, 3.10, 3.020, 1.75, .2, 0, 0, 0, 22),
    6: SocketHead(12.16, 3.72, 4.020, 2.20, .25, 0, 0, 0, 24),
    8: SocketHead(16.43, 4.96, 5.020, 2.90, .4, 0, 0, 0, 28),
    10: SocketHead(20.69, 6.20, 6.020, 3.50, .4, 0, 0, 0, 32),
    12: SocketHead(24.81, 7.44, 8.025, 4.30, .6, 0, 0, 0, 36),
    16: SocketHead(30.61, 8.80, 10.025, 4.80, .6, 0, 0, 0, 48),
    20: SocketHead(36.75, 10.16, 12.032, 5.60, .8, 0, 0, 0, 60),
}

# GB/T 70.4-2025: dc max, dk max, h max and b reference.
# The standard drawing specifies a smooth crown; choose the arc within the envelope.
FLANGES = {
    3: (6.9, 5.2, .7, 18), 4: (9.4, 7.2, .8, 20),
    5: (11.8, 8.8, 1., 22), 6: (13.6, 10., 1.2, 24),
    8: (17.8, 13.2, 1.5, 28), 10: (21.9, 16.5, 2., 32),
    12: (26., 19.4, 2.4, 36), 16: (34., 26., 2.8, 48),
}
FLANGE_HEADS = {
    d: replace(BUTTON_HEADS[d], diameter=dc, thread_reference=b)
    for d, (dc, _, _, b) in FLANGES.items()
}

# GB/T 65-2016 / ISO 1207:2011: dk max, k max, n min, t min, r min.
SLOTTED_HEADS = {
    2.5: SocketHead(4.5, 1.8, .66, .70, .1, 3.1, 0, .70, 25),
    3: SocketHead(5.5, 2., .86, .85, .1, 3.6, 0, .75, 25),
    4: SocketHead(7., 2.6, 1.26, 1.10, .2, 4.7, 0, 1.1, 38),
    5: SocketHead(8.5, 3.3, 1.26, 1.30, .2, 5.7, 0, 1.3, 38),
    6: SocketHead(10., 3.9, 1.66, 1.60, .25, 6.8, 0, 1.6, 38),
    8: SocketHead(13., 5., 2.06, 2., .4, 9.2, 0, 2., 38),
    10: SocketHead(16., 6., 2.56, 2.40, .4, 11.2, 0, 2.4, 38),
}

# GB/T 5783-2025 / ISO 4017:2022. Outer bearing diameter minimum,
# washer-face height (a representative value in the c range), r minimum, da max.
HEX_DETAILS = {
    2.5: (4.34, .175, .10, 3.1), 3: (4.84, .275, .10, 3.6),
    4: (6.20, .275, .20, 4.7), 5: (7.20, .325, .20, 5.7),
    6: (8.88, .325, .25, 6.8), 8: (11.63, .375, .40, 9.2),
    10: (14.63, .375, .40, 11.2), 12: (16.63, .375, .60, 13.7),
    16: (22.49, .50, .60, 17.7), 20: (28.19, .50, .80, 22.4),
    24: (33.61, .50, .80, 26.4),
}

PRODUCTS = {
    'socket': ('内六角圆柱头', 'GB/T 70.1-2008'),
    'button': ('内六角平圆头', 'GB/T 70.2-2025'),
    'countersunk': ('内六角沉头', 'GB/T 70.3-2023'),
    'flange_button': ('内六角平圆头凸缘', 'GB/T 70.4-2025'),
    'slotted': ('开槽圆柱头', 'GB/T 65-2016'),
    'hex': ('六角头', 'GB/T 5782-2025'),
}
SOCKET_HEADS = {'socket': CAP_HEADS, 'button': BUTTON_HEADS,
                'countersunk': COUNTERSUNK_HEADS, 'flange_button': FLANGE_HEADS}
DRIVE_HEADS = {**SOCKET_HEADS, 'slotted': SLOTTED_HEADS}
CROWN_TYPES = ('button', 'flange_button')
HEX_TYPES = ('hex', 'hex_full')


def socket_dimensions(head, diameter):
    return DRIVE_HEADS.get(head, {}).get(diameter)


def edge_details(p):
    r = p.head_width / 2
    spec = socket_dimensions(p.head_type, p.diameter)
    if p.head_type == 'socket':
        top = .065 * p.head_height
        bottom_limit = (p.head_width-spec.bearing_min)/2 if spec else .025*p.head_width
        if spec:
            bottom_limit = max(0., min(spec.edge_max, bottom_limit))
        return top, .65*bottom_limit
    dw, collar, _, _ = HEX_DETAILS.get(p.diameter, (p.head_width*.9, p.head_height*.07, 0, 0))
    bearing = r - min(max(0., (p.head_width-dw)/4), .04*p.head_width)
    return bearing, min(collar, .15*p.head_height)


def crown_geometry(p):
    spec = BUTTON_HEADS[p.diameter]
    outer = p.head_width/2
    rim = min(.06*p.head_height, .22)
    radius = spec.crown
    if p.head_type == 'flange_button':
        dc, dk, h, _ = FLANGES[p.diameter]
        outer *= dk / dc
        rim = h * p.head_height / spec.height
    flat = min(spec.flat_reference/2, .75*outer)
    dx, dz = outer-flat, p.head_height-rim
    chord = sqrt(dx*dx + dz*dz)
    offset = sqrt(radius*radius-chord*chord/4) / chord
    cx = (flat+outer)/2-dz*offset
    cz = -(p.head_height+rim)/2+dx*offset
    return flat, rim, radius, cx, cz, outer


def head_profile(p):
    """Sample the visible side profile from the same geometry used in CAD."""
    r, k = p.head_width/2, p.head_height
    if p.head_type == 'slotted':
        return [(-k,r),(0,r)]
    if p.head_type == 'countersunk':
        neck = p.seat_diameter/2+p.neck_radius
        return [(-k,r), (-r+neck,r), (0,neck)]
    if p.head_type in CROWN_TYPES:
        flat, rim, radius, cx, cz, outer = crown_geometry(p)
        points = [(-k,flat), *[
            (z,cx+sqrt(max(0.,radius*radius-(z-cz)**2)))
            for z in (-k+(k-rim)*i/24 for i in range(1,24))
        ], (-rim,outer)]
        if p.head_type == 'flange_button':
            points.append((-rim,r))
        return points + [(0,r)]
    if p.head_type == 'socket':
        top, bottom = edge_details(p)
        return [(-k,r-top),(-k+top,r),(-bottom,r),(0,r-bottom)]
    bearing, collar = edge_details(p)
    corner = r/cos(pi/6)
    return [(-k,r),(-k+(corner-r)*tan(pi/6),corner),
            (-collar-(corner-bearing)*tan(pi/12),corner),(-collar,bearing),(0,bearing)]


def socket_relief(p):
    """A light circular lead-in and a blind conical forming/drill relief."""
    s, k, t = p.socket_width, p.head_height, p.socket_depth
    spec = socket_dimensions(p.head_type, p.diameter)
    mouth = s/2/cos(pi/6) + .014*s
    lead = mouth-s/2
    floor_min = spec.floor_min if spec else .16*k
    blind = max(0., min(.18*s, .75*(k-t-floor_min)))
    if p.head_type in CROWN_TYPES:
        flat, _, radius, cx, cz, _ = crown_geometry(p)
        # On a crown the entrance intersects the dome above the six flats.
        if mouth > flat and mouth-cx < radius:
            lead += cz-sqrt(radius*radius-(mouth-cx)**2)+k
    return mouth, lead, blind


def make_head(p,cq):
    r, k = p.head_width/2, p.head_height
    if p.head_type == 'socket':
        top, bottom = edge_details(p)
        section = cq.Workplane('XZ').moveTo(0,-k)
        for z, rad in [(-k,r-top),(-k+top,r),(-bottom,r),(0,r-bottom),(0,0)]:
            section = section.lineTo(rad,z)
        return section.close().revolve().val()
    if p.head_type == 'slotted':
        return cq.Solid.makeCylinder(r,k,cq.Vector(0,0,-k))
    if p.head_type == 'countersunk':
        section = cq.Workplane('XZ').moveTo(0,-k)
        for z, rad in head_profile(p):
            section = section.lineTo(rad,z)
        return section.lineTo(0,0).close().revolve().val()
    if p.head_type in CROWN_TYPES:
        flat, rim, radius, cx, cz, outer = crown_geometry(p)
        middle = -(k+rim)/2
        xm = cx+sqrt(radius*radius-(middle-cz)**2)
        section = (cq.Workplane('XZ').moveTo(0,-k).lineTo(flat,-k)
                   .threePointArc((xm,middle),(outer,-rim)))
        if p.head_type == 'flange_button':
            section = section.lineTo(r,-rim)
        return section.lineTo(r,0).lineTo(0,0).close().revolve().val()

    bearing, collar = edge_details(p)
    corner = r/cos(pi/6)
    if bearing >= r:
        return cq.Workplane('XY').polygon(6,2*corner).extrude(-k).val()
    stock = cq.Workplane('XY').polygon(6,2*corner).extrude(-k).val()
    envelope = (cq.Workplane('XZ').moveTo(0,-k).lineTo(r,-k)
                .lineTo(corner+.01,-k+(corner+.01-r)*tan(pi/6))
                .lineTo(corner+.01,-collar-(corner+.01-bearing)*tan(pi/12))
                .lineTo(bearing,-collar).lineTo(bearing,0).lineTo(0,0)
                .close().revolve().val())
    return stock.intersect(envelope).clean()


def cut_socket(p, bolt, cq):
    k, s, t = p.head_height, p.socket_width, p.socket_depth
    epsilon = .0001
    mouth, lead, blind = socket_relief(p)
    key = (cq.Workplane('XY').polygon(6, s/cos(pi/6)).extrude(t+epsilon)
           .val().translate((0,0,-k-epsilon)))
    # A circular shallow countersink gives a real entry chamfer on each flat.
    entry = cq.Solid.makeCone(mouth+epsilon, s/2*.97, lead+.015*s+epsilon,
                              cq.Vector(0,0,-k-epsilon))
    if blind > .005:
        drill = cq.Solid.makeCone(.96*s/2, 0, blind+epsilon, cq.Vector(0,0,-k+t-epsilon))
        return bolt.cut(key,entry,drill).clean()
    return bolt.cut(key,entry).clean()


def cut_slot(p, bolt, cq):
    width, depth = p.socket_width, p.socket_depth
    reach = p.head_width + 2.
    slot = cq.Solid.makeBox(width,reach,depth+.01,
                           cq.Vector(-width/2,-reach/2,-p.head_height-.01))
    return bolt.cut(slot).clean()


def neck_reduction(p):
    """Local relief for the larger underhead radius of fully threaded button heads."""
    if p.head_type not in CROWN_TYPES or p.segments or p.thread_length != p.length:
        return 0.
    spec = socket_dimensions(p.head_type,p.diameter)
    if spec is None:
        return 0.
    excess = p.diameter/2+p.neck_radius-spec.transition_max/2
    return max(0., excess)


def threaded_tip(p, span):
    # GB/T 2 representative rolled end (small fasteners) or 45° chamfer.
    # Keep the end just below the basic minor diameter to avoid
    # a tangential Boolean where the cone would meet the helical root.
    depth = .625*p.pitch
    rolled = span.diameter <= 4
    axial = depth*(1.24 if rolled else 1)
    return axial, depth, rolled


def _tip_profile(cq, radius, radial_drop, axial, end, rolled, outer):
    z = end - axial
    section = cq.Workplane('XZ').moveTo(outer, z).lineTo(radius+.0001, z)
    if rolled:
        return section.threePointArc((radius-.24*radial_drop, z+.57*axial),
                                    (radius-radial_drop, end))
    return section.lineTo(radius-radial_drop, end)


def _tip_issue(candidate, bolt, cq, end, cap_radius, maximum_removal):
    from OCP.BRepAdaptor import BRepAdaptor_Surface

    if not candidate.isValid() or len(candidate.Solids()) != 1:
        return '切削结果不是有效的单一实体'
    # Query the plane itself. An integrated face centroid can be unreliable
    # on small faces or faces with sliver edges near the helix seam.
    cap_area = 0.
    axial_tolerance = 1e-5
    for face in candidate.Faces():
        if face.geomType() == 'PLANE':
            plane = BRepAdaptor_Surface(face.wrapped).Plane()
            if (abs(plane.Location().Z()-end) < axial_tolerance
                    and abs(plane.Axis().Direction().Z()) > .9999):
                cap_area += face.Area()
    expected = pi*cap_radius**2
    if abs(cap_area-expected) > max(1e-6, expected*1e-4):
        return f'尾端面面积 {cap_area:.8g} mm²，目标 {expected:.8g} mm²'
    if (not candidate.isInside(cq.Vector(0,0,end-1e-4))
            or candidate.isInside(cq.Vector(0,0,end+1e-4))):
        return '实体轴向端点与公称长度不符'
    if not volume_change_between(bolt,candidate,-maximum_removal-1e-6,-1e-7):
        return '切除量超出允许范围或没有切除材料'
    return None


def trim_threaded_end(p, bolt, span, cq):
    """Form the specified tip, retrying with a complementary CAD envelope."""
    axial, drop, rolled = threaded_tip(p,span)
    radius = span.diameter/2
    end = span.end
    cap_radius = radius-drop
    upper = end+axial
    outer = radius+p.pitch
    profile = _tip_profile(cq,radius,drop,axial,end,rolled,outer)
    cutter = profile.lineTo(cap_radius,upper).lineTo(outer,upper).close().revolve().val()

    reasons = []

    def try_tool(tool, operation, angles, label):
        for angle in angles:
            try:
                moved = tool.rotate((0,0,0),(0,0,1),angle) if angle else tool
                result = operation(moved)
                try:
                    candidates = (result.clean(), result)
                except RuntimeError:
                    candidates = (result,)
                issues = []
                for candidate in candidates:
                    issue = _tip_issue(candidate,bolt,cq,end,cap_radius,pi*radius**2*axial)
                    if issue is None:
                        return candidate
                    issues.append(issue)
                reasons.append(f'{label} {angle:g}°：'+'、'.join(dict.fromkeys(issues)))
            except Exception as ex:
                reasons.append(f'{label} {angle:g}°：{type(ex).__name__}: {ex}')
        return None

    result = try_tool(cutter, bolt.cut, (0.,71.,163.,251.), '切削')
    if result is not None:
        return result

    # Keep all upstream geometry inside a wide revolution. Only the two
    # profile edges at the tail can intersect the bolt. Its axial caps are
    # beyond the bolt ends, so the keeper introduces no coincident end face.
    outer = max(p.head_width, *(s.diameter for s in p.spans(merge=True))) + p.pitch
    lower = -p.head_height-p.pitch
    section = _tip_profile(cq,radius,drop,axial,end,rolled,outer)
    keeper = (section.lineTo(cap_radius,upper).lineTo(0,upper).lineTo(0,lower)
              .lineTo(outer,lower).close().revolve().val())
    result = try_tool(keeper, bolt.intersect, (23.,109.,211.,317.), '包络截取')
    if result is not None:
        return result

    kind = '滚制圆弧端' if rolled else '45° 倒角'
    raise ValueError(
        f'尾端{kind}未通过实体与尺寸检查，d={span.diameter:g} mm，'
        f'P={p.pitch:g} mm，端面 z={end:g} mm。\n'+'\n'.join(reasons))
