"""B-Rep for stepped shanks with explicit, phase-aligned threaded spans."""
import math

from cad_kernel import volume_change_between
from shank import runout
from fastener_heads import make_head, trim_threaded_end


def retains_thread(body, span, pitch, neck):
    from OCP.BRepClass3d import BRepClass3d_SolidClassifier
    from OCP.TopAbs import TopAbs_IN
    from OCP.gp import gp_Pnt

    classifier = BRepClass3d_SolidClassifier(body.wrapped)
    lead, exit = runout(span, pitch, neck)
    z = (span.start+lead+span.end-exit)/2
    r = span.diameter/2-.28*pitch
    state = None
    for i in range(24):
        angle = i*math.tau/24
        classifier.Perform(gp_Pnt(r*math.cos(angle), r*math.sin(angle), z), 1e-6)
        inside = classifier.State() == TopAbs_IN or classifier.IsOnAFace()
        if state is not None and inside != state:
            return True
        state = inside
    return False


def clean_candidates(body):
    try:
        yield body.clean()
    except RuntimeError:
        pass
    yield body


def make_segmented_bolt(p, cq, checked, threaded_solid, log):
    spans = p.spans(merge=True)
    pitch = p.pitch
    radius = spans[0].diameter/2
    neck = p.neck_radius
    section = cq.Workplane('XZ').moveTo(0,0)
    if neck > 1e-6:
        arc = neck*(1-2**-.5)
        section = section.lineTo(radius+neck,0).threePointArc((radius+arc,arc),(radius,neck))
    else:
        section = section.lineTo(radius,0)
    terminal=spans[-1]
    end=terminal.end
    previous = radius
    breaks = p.shank_edge_breaks(spans)
    for span,(chamfer_in,chamfer_out) in zip(spans,breaks):
        radius = span.diameter/2
        start_r = radius-chamfer_in
        if start_r != previous:
            section = section.lineTo(start_r,span.start)
        if chamfer_in:
            section = section.lineTo(radius,span.start+chamfer_in)
        if span.kind == 'thread':
            carrier_root = radius-.633434*pitch
            lead, exit = runout(span,pitch,neck)
            section = section.lineTo(carrier_root,span.start+lead)
            if span==terminal:
                end=span.end-min(.15*pitch,exit*.4)
                section = section.lineTo(carrier_root,end)
            else:
                section = section.lineTo(carrier_root,span.end-exit).lineTo(radius,span.end-chamfer_out)
        else:
            section = section.lineTo(radius,span.end-chamfer_out)
        previous = radius-chamfer_out
        if chamfer_out:
            section = section.lineTo(previous,span.end)
    carrier = checked('头杆圆角与分段坯体',lambda:section.lineTo(0,end).close().revolve().val())
    head = checked('头部成形',lambda:make_head(p,cq))
    log('@progress:25')
    teeth = []
    trim_after_join = False
    for i, span in enumerate(spans,1):
        if span.kind != 'thread':
            continue
        log(f'第 {i} 段螺纹 · z={span.start:g}–{span.end:g} mm')
        # All spans share the same helix intercept, including the nut cutter.
        lead, exit = runout(span,pitch,neck)
        start = span.start+.22*lead
        stop = span.end if span==terminal else span.end-.22*exit
        angle = (17.+360.*start/pitch)%360.
        tooth = threaded_solid(pitch,round(stop-start,9),span.diameter/2,p.root_radius).copy()
        tooth=tooth.rotate((0,0,0),(0,0,1),angle).translate((0,0,start))
        if span==terminal:
            try:
                tooth=trim_threaded_end(p,tooth,span,cq)
            except ValueError:
                trim_after_join=True
        teeth.append((span,tooth))

    for seam in ((103.,41.,197.,283.) if len(teeth)>1 else (41.,103.,197.,283.)):
        stock = carrier.rotate((0,0,0),(0,0,1),seam)
        try:
            body = checked('头杆连接',lambda:head.fuse(stock).clean())
            if len(teeth)>1:
                try:
                    candidate = checked('分段螺纹连接',lambda:body.fuse(*(tooth for _,tooth in teeth)).clean())
                    if trim_after_join:
                        candidate=trim_threaded_end(p,candidate,terminal,cq)
                    if all(retains_thread(candidate,span,pitch,neck) for span,_ in teeth):
                        log('@progress:45')
                        return candidate
                except Exception:
                    pass
            for span, tooth in teeth:
                combined = body.fuse(tooth)
                for candidate in clean_candidates(combined):
                    if (candidate.isValid() and len(candidate.Solids()) == 1
                            and volume_change_between(body,candidate,1e-6)
                            and retains_thread(candidate,span,pitch,neck)):
                        body = candidate
                        break
                else:
                    raise ValueError(f'z={span.start:g}–{span.end:g} mm 的牙型连接未通过检查')
            if trim_after_join:
                body=trim_threaded_end(p,body,terminal,cq)
            if all(retains_thread(body,span,pitch,neck) for span,_ in teeth):
                log('@progress:45')
                return body
        except Exception as ex:
            failure = ex
            log(f'分段连接检查未通过（接缝 {seam:g}°）· {ex}')
    raise ValueError('分段杆身未能保留完整牙型，请检查日志中的分段位置') from failure
