"""Recompute R01 nominal engineering estimates, writing calculations.json beside this file."""
import hashlib
import json
import math
from pathlib import Path

ROOT = Path(__file__).resolve().parent
# Explicit source checks guard against stale geometry assumptions.
required = {
    "fluid/build.py": (
        "ring(7,6,57,25)", "cyl(5.97,81,1)", "ring(5.98,.65,57,.8)",
        "piston(0,g,'F03',6,59.5)", "depth,width,free=.80,1.25,.95",
        "z+.85+width,.85", "cyl(.60,80.8,5.4)", "cyl(1.35,80.8,1.8,3.7)",
        "piston(x,g,'F11',8.8,15)", "ring(10,1,9,1,x)", "cyl(10,44,2,x)",
        "cyl(.90,5,10,x).fuse(cyl(5,4,1,x))", "cyl(1.05,49,.30,x)",
        "cyl(1.20,83.5,.6,0,3.7)"),
    "head/build.py": ("1.49*cos(i*2*pi/48)", "88.85+i*.84/48", "range(241)",
                      'tube("HD05","Wick heater winding",pts,.15', "(.82,86)"),
    "chassis/build.py": ("vent=Part.makeCylinder(.42,12", "55.18", "(10.50,54.68)",
                         "1.8,1.36,1.85", "cyl(.65,55.13,1)"),
    "power/build.py": ("pts,.18,None", "pts,.38,.183", "],.68,.382", "Heater terminal mating pad"),
}

def audit():
    hashes = {}
    for source, tokens in required.items():
        data = (ROOT / source).read_bytes()
        for token in tokens:
            if token.encode() not in data:
                raise ValueError(f"Review changed geometry in {source}: missing {token}")
        hashes[source] = hashlib.sha256(data).hexdigest()
    return hashes

def circle(d):
    return math.pi * d*d / 4

def flow_resistance(length_mm, diameter_mm, viscosity=1.8e-5):
    """Pa per (mL/s), steady ideal straight laminar gas passage."""
    return 128*viscosity*(length_mm/1000)/(math.pi*(diameter_mm/1000)**4)*1e-6

def calculate():
    area = circle(12)
    piston_height = .85+1.25+.85
    shown_stroke = 81-(59.5+piston_height)
    max_stroke = 81-(57.8+piston_height)
    refill_area = circle(17.6)
    # Tube/polyline length and smooth mathematical helix for independent cross-check.
    points = [(1.49*math.cos(i*math.tau/48), 1.49*math.sin(i*math.tau/48), 88.85+i*.84/48)
              for i in range(241)]
    length = sum(math.dist(a,b) for a,b in zip(points,points[1:]))
    helix = 5*math.hypot(math.tau*1.49,.84)
    wire_area = circle(.30)
    resistance = 1.09*(length/1000)/wire_area
    outlet = circle(1.20)*(86-81)
    septum = circle(2.70)*(82.6-81)
    radial = flow_resistance(10.50,.84)
    axial = flow_resistance(57.8-55.18,1.30)
    assert 0 < (helix-length)/helix < .001
    assert math.isclose(length, 240*math.hypot(2*1.49*math.sin(math.pi/48),.84/48))
    assert math.isclose(area*(max_stroke-shown_stroke),area*(59.5-57.8))
    assert math.isclose(flow_resistance(10.50,.84*.5),16*radial)
    return {
        "source_sha256": audit(),
        "units": "embedded in key names; nominal analytical results",
        "reservoir": {"bore_area_mm2":area,"follower_height_mm":piston_height,
            "upper_stroke_from_shown_mm":shown_stroke,"upper_sweep_from_shown_mL":area*shown_stroke/1000,
            "upper_full_geometric_stroke_mm":max_stroke,"upper_hard_stop_to_hard_stop_sweep_mL":area*max_stroke/1000,
            "geometric_sweep_lost_per_mm_end_margin_mL":area/1000,
            "manifold_outlet_uL":outlet,"blind_refill_branch_uL":septum,
            "idealized_fixed_passage_total_uL":outlet+septum,
            "follower_force_N_per_kPa":area/1000},
        "refill":{"bore_area_mm2":refill_area,"upper_sweep_from_current_liquid_chamber_mL":refill_area*(44-15-piston_height)/1000,
            "maximum_forward_stroke_before_thumbpad_hits_stop_mm":9-5,
            "stroke_limited_displacement_mL":refill_area*(9-5)/1000,
            "finger_force_N_per_kPa_without_friction":refill_area/1000},
        "vent":{"assumed_air_viscosity_Pa_s":1.8e-5,"radial_Pa_per_mL_s":radial,"axial_Pa_per_mL_s":axial,
            "combined_Pa_per_mL_s":radial+axial,
            "combined_if_radial_diameter_reduced_20pct_Pa_per_mL_s":radial/(.8**4)+axial},
        "fits":{"gland_squeeze_fraction":1-.80/.95,"gland_area_fill_fraction":circle(.95)/(.80*1.25),
            "piston_land_radial_gap_mm":.10,"refill_guide_radial_gap_mm":1.20-1.05,"feed_face_radial_margin_mm":.82-.60,
            "radial_conductor_core_to_jacket_mm":.183-.18,"radial_jacket_to_bushing_mm":.382-.38,
            "radial_bushing_to_bore_mm":.68-.68,"jacket_to_keyway_side_mm":1.36/2-.38},
        "winding":{"polyline_mm":length,"ideal_helix_mm":helix,"wire_section_mm2":wire_area,
            "assumed_candidate_nikrothal80_resistivity_ohm_mm2_m_at_20C":1.09,"coil_only_ohm_at_20C":resistance,
            "coil_only_ohm_at_100C_uniform_datasheet_Ct_1_01":resistance*1.01,
            "ideal_active_wire_mass_g":length*wire_area*.00830},
    }

if __name__ == "__main__":
    result = calculate()
    (ROOT/"calculations.json").write_text(json.dumps(result,indent=2)+"\n")
    print(json.dumps({k:v for k,v in result.items() if isinstance(v,dict) and k!="source_sha256"},indent=2))
