"""
heath frame: centre-line CAD model, mass estimate and a 3D beam (frame) analysis for a rear load.

Units: mm, N, MPa. Axes: x forward, y left, z up, origin at the bottom bracket.
Geometry is taken from the same key points that build the 3D model (build_bike.py).
EVERYTHING under ASSUMPTIONS is a guess until the real tube spec is filled in.
Run:  python3 frame_analysis.py            (writes heath_frame.step and prints the results)
"""
import numpy as np, json, sys

# ----------------------------- ASSUMPTIONS: edit these -----------------------------
MATERIAL = dict(name='4130 chromoly steel (as welded)', E=205000.0, G=80000.0, rho=7.85e-6, yield_=435.0, weld_fatigue=120.0)
#           outer dia, wall (mm)
# Recommended set. The rear struts land just above the dropouts (STRUT_LANDS), which is what makes the rear end strong:
# about 81 kg on the rails in this model. As drawn in BikeCAD the frame was long bar 38 x 0.9, seat tube 28.6 x 0.9,
# down tube 35 x 0.9, seat stays 16 x 1.0, chain stays 17 x 1.2, struts 16 x 0.9, landing two-thirds down the stays (about 20 kg).
SECTIONS = {'long bar': (38.0, 1.5), 'seat tube': (28.6, 1.2), 'down tube': (35.0, 0.9), 'head tube': (37.0, 1.1),
            'seat stay': (19.0, 1.2), 'chain stay': (19.0, 1.2), 'rear strut': (16.0, 1.5), 'front strut': (16.0, 0.9),
            'fork (stand-in)': (30.0, 2.5)}
STRUT_LANDS = 0.92                                 # how far down the seat stay the rear strut lands (0.67 as first drawn)
RIDER_KG, REAR_KG, FRONT_KG = 80.0, 35.0, 0.0     # rider; load on the rear rails (child + seat); load on the front deck
BUMP = 2.5                                         # dynamic factor for the "hard bump" case
G_ = 9.81
# -------------------------------------------------------------------------------------

# key points (mm), as in build_bike.py
BB = np.zeros(3); R_AX = np.array([-375.4, 0, -33.6]); F_AX = np.array([572.6, 0, -33.6])
sa = np.radians(73.0); st_dir = np.array([-np.cos(sa), 0, np.sin(sa)]); ht_dir = st_dir.copy()
ST_TOP = st_dir * 475.0; HT_BOT = np.array([443.0, 0, 242.0]); HT_TOP = HT_BOT + ht_dir * 223.0
GEO = json.load(open(sys.argv[1] if len(sys.argv) > 1 else 'geometry.json'))
bar_rear, bar_mid, bar_front, STRUT_TOP, DT_END = (np.array(GEO[k]) for k in ('bar_rear', 'bar_mid', 'bar_front', 'STRUT_TOP', 'DT_END'))
REAR_RACK_X = [bar_rear[0] + 25, bar_rear[0] + 175, bar_rear[0] + 325]          # the three gussets of the rear rails
FRONT_RACK_X = GEO['front_rack_x']

def on_line(p0, p1, q0, q1):
    """Point on line p0-p1 closest to line q0-q1 (both in the x-z plane)."""
    A = np.array([[p1[0] - p0[0], -(q1[0] - q0[0])], [p1[2] - p0[2], -(q1[2] - q0[2])]]); t, _ = np.linalg.solve(A, [q0[0] - p0[0], q0[2] - p0[2]])
    return p0 + (p1 - p0) * t
def bar_at(x):
    a, b = (bar_rear, bar_mid) if x <= bar_mid[0] else (bar_mid, bar_front); return a + (b - a) * (x - a[0]) / (b[0] - a[0])

N = {}                                             # nodes
def node(name, p): N[name] = np.asarray(p, float); return name
node('BB', BB); node('ST_TOP', ST_TOP); node('HT_BOT', HT_BOT); node('HT_TOP', HT_TOP); node('DT_END', DT_END); node('F_AX', F_AX)
node('BAR_ST', on_line(bar_rear, bar_mid, BB, ST_TOP)); node('BAR_HT', on_line(bar_mid, bar_front, HT_BOT, HT_TOP))
node('BAR_REAR', bar_rear); node('BAR_MID', bar_mid); node('BAR_FRONT', bar_front); node('BAR_FSTRUT', STRUT_TOP)
node('BAR_RSTRUT', bar_rear + [103, 0, 0])
for i, x in enumerate(REAR_RACK_X): node(f'RR{i}', bar_at(x))
for i, x in enumerate(FRONT_RACK_X): node(f'FR{i}', bar_at(x))
M = []                                             # members: (name, section, node a, node b)
def member(sec, a, b): M.append((f'{sec}: {a}-{b}', sec, a, b))
for s, sgn in (('L', 1), ('R', -1)):
    ss_top = ST_TOP - st_dir * 40 + [0, sgn * 14, 0]; drop = R_AX + [0, sgn * 68, 0]; ss_bot = drop + [0, 0, 8]
    c = ss_top + (ss_bot - ss_top) * STRUT_LANDS
    node(f'SS_TOP_{s}', ss_top); node(f'DROP_{s}', drop); node(f'SS_MID_{s}', c); node(f'CS_BEND_{s}', BB + [-120, sgn * 48, -11]); node(f'CS_BB_{s}', BB + [-18, sgn * 26, 0])
    member('seat stay', f'SS_TOP_{s}', f'SS_MID_{s}'); member('seat stay', f'SS_MID_{s}', f'DROP_{s}')
    member('chain stay', f'CS_BB_{s}', f'CS_BEND_{s}'); member('chain stay', f'CS_BEND_{s}', f'DROP_{s}')
    member('rear strut', 'BAR_RSTRUT', f'SS_MID_{s}')
    member('head tube', 'BB', f'CS_BB_{s}')                        # the bottom-bracket shell, stiff
node('ST_SS', ST_TOP - st_dir * 40)
for s in ('L', 'R'): member('head tube', 'ST_SS', f'SS_TOP_{s}')   # short stiff link: stays to the seat tube
# the long bar, node to node from rear to front
bar_nodes = sorted([n for n in N if n.startswith(('BAR_', 'RR', 'FR'))], key=lambda n: N[n][0])
for a, b in zip(bar_nodes[:-1], bar_nodes[1:]):
    if np.linalg.norm(N[a] - N[b]) > 1e-6: member('long bar', a, b)
st_nodes = sorted(['BB', 'BAR_ST', 'ST_SS', 'ST_TOP'], key=lambda n: N[n][2])
for a, b in zip(st_nodes[:-1], st_nodes[1:]): member('seat tube', a, b)
ht_nodes = sorted(['HT_BOT', 'DT_END', 'BAR_HT', 'HT_TOP'], key=lambda n: N[n][2])
for a, b in zip(ht_nodes[:-1], ht_nodes[1:]): member('head tube', a, b)
member('down tube', 'BB', 'DT_END'); member('front strut', 'DT_END', 'BAR_FSTRUT'); member('fork (stand-in)', 'HT_BOT', 'F_AX')

def props(sec):
    D, t = SECTIONS[sec]; d = D - 2 * t; A = np.pi / 4 * (D**2 - d**2); I = np.pi / 64 * (D**4 - d**4); return A, I, 2 * I, I / (D / 2)

# ----------------------------- 3D frame solver (direct stiffness) -----------------------------
names = list(N); idx = {n: i for i, n in enumerate(names)}; ndof = 6 * len(names)
def k_local(E, G, A, I, J, L):
    k = np.zeros((12, 12)); a = E * A / L; t = G * J / L; b = 12 * E * I / L**3; c = 6 * E * I / L**2; d = 4 * E * I / L; e = 2 * E * I / L
    for i, j, v in ((0, 0, a), (0, 6, -a), (6, 6, a), (3, 3, t), (3, 9, -t), (9, 9, t),
                    (1, 1, b), (1, 5, c), (1, 7, -b), (1, 11, c), (5, 5, d), (5, 7, -c), (5, 11, e), (7, 7, b), (7, 11, -c), (11, 11, d),
                    (2, 2, b), (2, 4, -c), (2, 8, -b), (2, 10, -c), (4, 4, d), (4, 8, c), (4, 10, e), (8, 8, b), (8, 10, c), (10, 10, d)):
        k[i, j] = v; k[j, i] = v
    return k
def rot(p0, p1):
    x = (p1 - p0) / np.linalg.norm(p1 - p0); ref = np.array([0, 0, 1.0]) if abs(x[2]) < 0.95 else np.array([0, 1.0, 0])
    y = np.cross(ref, x); y /= np.linalg.norm(y); z = np.cross(x, y); R = np.vstack([x, y, z]); T = np.zeros((12, 12))
    for i in range(4): T[3 * i:3 * i + 3, 3 * i:3 * i + 3] = R
    return T
E_, G__ = MATERIAL['E'], MATERIAL['G']; K = np.zeros((ndof, ndof)); els = []
for name, sec, a, b in M:
    A, I, J, Z = props(sec); p0, p1 = N[a], N[b]; L = np.linalg.norm(p1 - p0); T = rot(p0, p1); kl = k_local(E_, G__, A, I, J, L)
    dofs = np.r_[6 * idx[a] + np.arange(6), 6 * idx[b] + np.arange(6)]; K[np.ix_(dofs, dofs)] += T.T @ kl @ T; els.append((name, sec, dofs, T, kl, A, Z, L))
fixed = [6 * idx['DROP_L'] + i for i in (0, 1, 2)] + [6 * idx['DROP_R'] + i for i in (0, 2)] + [6 * idx['F_AX'] + i for i in (1, 2)] + [6 * idx['F_AX'] + 3]
free = np.setdiff1d(np.arange(ndof), fixed)

def solve(rider, rear, front, factor):
    F = np.zeros(ndof); down = lambda n, kg: F.__setitem__(6 * idx[n] + 2, F[6 * idx[n] + 2] - kg * G_ * factor)
    down('ST_TOP', rider * 0.7); down('BB', rider * 0.3)
    for i in range(len(REAR_RACK_X)): down(f'RR{i}', rear / len(REAR_RACK_X))
    for i in range(len(FRONT_RACK_X)): down(f'FR{i}', front / len(FRONT_RACK_X))
    u = np.zeros(ndof); u[free] = np.linalg.solve(K[np.ix_(free, free)], F[free]); out = {}
    for name, sec, dofs, T, kl, A, Z, L in els:
        f = kl @ (T @ u[dofs]); worst = 0
        for e in (0, 6): worst = max(worst, abs(f[e]) / A + np.hypot(f[e + 4], f[e + 5]) / Z)      # axial + bending at each end
        out.setdefault(sec, (0, ''));
        if worst > out[sec][0]: out[sec] = (worst, name)
    react = K @ u - F
    return out, u, {'rear axle': (react[6 * idx['DROP_L'] + 2] + react[6 * idx['DROP_R'] + 2]) / G_, 'front axle': react[6 * idx['F_AX'] + 2] / G_}

def report(title, rider, rear, front, factor):
    out, u, react = solve(rider, rear, front, factor)
    print(f'\n{title}\n  wheel loads: rear {react["rear axle"]:.0f} kg, front {react["front axle"]:.0f} kg (x{factor:g})')
    print(f'  {"tube":<18}{"peak stress MPa":>16}{"vs yield":>10}{"vs weld fatigue":>17}   where')
    for sec, (s, where) in sorted(out.items(), key=lambda kv: -kv[1][0]):
        if sec in ('fork (stand-in)',): continue
        print(f'  {sec:<18}{s:>16.0f}{MATERIAL["yield_"] / s:>9.1f}x{MATERIAL["weld_fatigue"] / s:>16.1f}x   {where.split(": ")[1]}')
    print(f'  deflection at the rear end of the bar: {abs(u[6 * idx["BAR_REAR"] + 2]):.2f} mm')
    return out

if __name__ == '__main__':
    mass = {}
    for name, sec, a, b in M:
        if sec == 'fork (stand-in)' or 'CS_BB' in name and sec == 'head tube' or 'ST_SS-SS' in name: continue
        mass[sec] = mass.get(sec, 0) + props(sec)[0] * np.linalg.norm(N[a] - N[b]) * MATERIAL['rho']
    print(f'Material: {MATERIAL["name"]}  (yield {MATERIAL["yield_"]:.0f} MPa, weld fatigue allowable {MATERIAL["weld_fatigue"]:.0f} MPa: both assumed)')
    print('Tube masses (kg): ' + ', '.join(f'{k} {v:.2f}' for k, v in mass.items()) + f'   | frame tubes total {sum(mass.values()):.2f} kg (no fork, racks, BB shell, dropouts)')
    report(f'A. Standing still: rider {RIDER_KG:.0f} kg + {REAR_KG:.0f} kg on the rear rails', RIDER_KG, REAR_KG, FRONT_KG, 1.0)
    report(f'B. Hard bump (x{BUMP:g}): rider {RIDER_KG:.0f} kg + {REAR_KG:.0f} kg on the rear rails', RIDER_KG, REAR_KG, FRONT_KG, BUMP)
    report(f'C. Rear load alone on a hard bump (x{BUMP:g}): {REAR_KG:.0f} kg, no rider', 0.0, REAR_KG, 0.0, BUMP)
    # the largest rear load that keeps every frame tube under the weld-fatigue allowable on a hard bump, rider aboard
    lo, hi = 0.0, 400.0
    for _ in range(40):
        mid = (lo + hi) / 2; o, _, _ = solve(RIDER_KG, mid, FRONT_KG, BUMP)
        if max(v[0] for k, v in o.items() if k != 'fork (stand-in)') < MATERIAL['weld_fatigue']: lo = mid
        else: hi = mid
    print(f'\nLargest rear load with every tube under the weld-fatigue allowable on a hard bump, {RIDER_KG:.0f} kg rider aboard: {lo:.0f} kg')
    try:                                               # centre-line tubes as a STEP assembly
        import cadquery as cq
        asm = cq.Assembly(name='heath_frame')
        for i, (name, sec, a, b) in enumerate(M):
            if sec == 'fork (stand-in)': continue
            D, t = SECTIONS[sec]; p0, p1 = N[a], N[b]; L = float(np.linalg.norm(p1 - p0)); d = (p1 - p0) / L
            tube = cq.Workplane(cq.Plane(origin=tuple(p0), xDir=tuple(np.cross(d, [0, 1, 0]) if abs(d[1]) < 0.9 else np.cross(d, [1, 0, 0])), normal=tuple(d))).circle(D / 2).circle(D / 2 - t).extrude(L)
            asm.add(tube, name=f'{i:02d}_{sec.replace(" ", "_")}')
        asm.save('heath_frame.step'); print('\nwrote heath_frame.step (hollow tubes on their centre lines, ends not mitred)')
    except Exception as e: print('STEP export skipped:', e)
