"""Active Motif ATAC-Seq Express High-Throughput 53158 A2 on Flex, 8–48 samples, robot Steps 1–26.

Nuclei are prepared by hand in input plate P1 (cell wash, 100 uL lysis and the 500 x g,
10 minute, 4 C nuclei spin), leaving an explicitly assumed 10 uL nuclei residual per
active well. The kit's pre-indexed breakaway plate P2 (4 uL indexed Tn5 already in each
well) is seated on the Thermocycler at setup; the run cools the block to 4 C declaring
that real 4 uL volume, and the operator places the chilled P1 at C2 at the loading
prompt. Step 1 adds 21 uL enzyme-free
TMM to each P1 column, resuspends, and with the same tips moves the nominal 31 uL into
the matched P2 column (35 uL nominal with the Tn5); P1 is then parked at D4. Binding and
silica cleanup stay in P2; P3 on the Thermocycler is precharged with 16.5 uL universal PCR
premix (one tip column for all wells), then receives 33.5 uL eluate per well with fresh
tips and mixing, then the SPRI cleanup; libraries finish in P4. Every tip
pickup is a complete column of eight. The breakaway-plate fit and the 163 uL 4 C hold are
user assumptions, not physically qualified.
"""

import time

from opentrons import protocol_api


metadata = {
    "protocolName": "ATAC-Seq Express High-Throughput 53158 A2 — Flex — 8–48 samples — robot Steps 1–26",
    "author": "Andres / protocol adaptation",
    "description": (
        "Active Motif 53158 A2 with the pre-indexed Tn5 kit plate, complete eight-sample columns, one run of "
        "robot Steps 1–26 after manual nuclei preparation. Kit plate P2 starts on the Thermocycler, cooled to 4 C "
        "with its real 4 uL/well declared; nuclei input plate P1 at C2 receives 21 uL enzyme-free TMM and its "
        "nominal 31 uL is moved with the same tips into the matched P2 well holding 4 uL Tn5; P1 parks at D4. "
        "Binding, 180 uL silica washes and 35 uL silica elution in P2; P3 on the Thermocycler precharged with "
        "16.5 uL universal PCR premix, then 33.5 uL eluate added and mixed; SPRI cleanup in P3; 18 uL libraries recovered into P4. "
        "P1000 200 uL racks at A2 and D2 used directly; P50 50 uL rack at A3 only; Heater-Shaker idle at D1. "
        "Breakaway-plate fit (Bio-Rad geometry surrogate) and the 163 uL 4 C hold are not qualified."
    ),
    "apiLevel": "2.27",
}
requirements = {"robotType": "Flex"}

PCR_PLATE = "biorad_96_wellplate_200ul_pcr"
# P2 is the kit's pre-indexed breakaway plate in its carrier. The user assumes it fits the
# Thermocycler, Magnetic Block, deck slots and gripper; the Bio-Rad definition is loaded
# as an explicit GEOMETRY SURROGATE, not as a validated custom definition.
KIT_PLATE_SURROGATE = PCR_PLATE
WORKING_SLOT = "C2"
P1_PARK_SLOT = "D4"
P1000_TIP_SLOTS = ("A2", "D2")  # Both racks are direct pickup positions at every count.
P50_TIP_SLOT = "A3"  # The only P50 rack position.
LIFT_SPEED_MM_S = 100  # Withdrawal from a well only; other moves keep the robot's default speed.
CELL_INPUT = 100000  # Inherited session input per active P1 well; visible constant, not a run choice.
SAMPLE_COUNTS = (8, 16, 24, 32, 40, 48)
DEFAULT_SAMPLE_COUNT = 48
# Source-use attribution only: "A" sources are consumed in Steps 1–6 and "B" sources
# in Steps 8–26 of the same run.
SECTION_A = "A"
SECTION_B = "B"
SAMPLES_PER_COLUMN = 8
NUCLEI_RESIDUAL_UL = 10.0  # Explicit assumption after the manual nuclei spin.
TMM_UL = 21.0  # 12.5 2x buffer + 1 10x PBS + 0.25 1% digitonin + 0.25 10% Tween-20 + 7 water; no enzyme.
TMM_RESERVE_FRACTION = 0.10
INPUT_MIX_UL = NUCLEI_RESIDUAL_UL + TMM_UL  # 31 uL nominal in P1, transferred in full.
TN5_UL = 4.0  # Indexed Tn5 pre-dispensed by the kit in each P2 well.
TAG_REACTION_UL = INPUT_MIX_UL + TN5_UL  # 35 uL nominal.
BINDING_BUFFER_UL = 125.0
BOUND_REACTION_UL = TAG_REACTION_UL + BINDING_BUFFER_UL  # 160 uL.
SILICA_BEADS_UL = 3.0
SILICA_WASH_UL = 180.0  # User override of the manual's 200 uL.
SILICA_ELUTION_UL = 35.0  # User choice; matches the manual.
PCR_INPUT_UL = 33.5  # Leaves 1.5 uL nominal over the silica beads.
PCR_PREMIX_UL = 16.5  # 10 Q5 buffer + 1 dNTP + 0.5 Q5 enzyme + 2.5 P5 + 2.5 P7 (25 uM).
PCR_REACTION_UL = PCR_INPUT_UL + PCR_PREMIX_UL  # 50 uL.
SPRI_UL = 60.0
ETHANOL_UL = 180.0
FINAL_ELUTION_UL = 20.0
FINAL_RECOVERY_UL = 18.0  # 20 uL elution; leave 2 uL to reduce bead carryover.
ELUTION_SOURCE_UL = SILICA_ELUTION_UL + FINAL_ELUTION_UL  # 55 uL per matched B3 well.

# Provisional engineering settings. Verify source immersion and recovery on the
# actual plates; these are programmed coordinates, not measured clearances.
SOURCE_CLEARANCE_MM = 1.0
BULK_CLEARANCE_MM = 1.0
MIN_LIQUID_CLEARANCE_MM = 0.3
LOW_CLEARANCE_MM = 0.5
TRANSFER_RATE_UL_S = 5.0
PCR_RESERVE_UL = 10.0
SILICA_RESERVE_UL = 4.0
ELUTION_RESERVE_UL = 5.0
SPRI_RESERVE_UL = 10.0
RESERVOIR_RESERVE_UL = 1000.0

FIRST_STEP = 1
# Kit index map by physical kit-plate well: i7 by row, i5 by column, with two
# physical-well exceptions that override the regular rule.
I7_BY_ROW = ("N701", "N702", "N703", "N704", "N705", "N706", "N707", "N708")
I5_BY_COLUMN = ("N505", "N506", "N507", "N508", "N510", "N511")
INDEX_EXCEPTIONS = {"D3": ("N709", "N507"), "G6": ("N709", "N511")}

STEP_TITLES = (
    "Add 21 uL TMM to P1, resuspend nuclei, transfer 31 uL into the matched pre-indexed P2 wells and park P1 at D4.",
    "Close the Thermocycler with the reusable seal for static tagmentation.",
    "Incubate at 37 C in the Thermocycler for 30 minutes without shaking.",
    "Open the Thermocycler after static tagmentation.",
    "Add 125 uL binding buffer to P2 on the Thermocycler and mix each nominal 160 uL reaction.",
    "Add 3 uL silica beads and mix the binding reactions.",
    "Five-minute hold on the pre-cooled 4 C Thermocycler; transfer P2 to the Magnetic Block.",
    "Magnetically collect silica beads and remove binding supernatant.",
    "First 180 uL silica wash with off-magnet resuspension.",
    "Second 180 uL silica wash with off-magnet resuspension.",
    "Clear residual silica wash and inspect bead drying.",
    "Elute silica-purified DNA in 35 uL for five minutes.",
    "Precharge P3 with 16.5 uL universal PCR premix, then transfer 33.5 uL DNA and mix 50 uL reactions.",
    "Stage the used kit plate P2 at A4.",
    "Verify the 50 uL PCR reactions are ready for amplification.",
    "Run the 50 uL ATAC PCR with ten cycles and the reusable seal.",
    "Add 60 uL SPRI beads and bind for five minutes.",
    "Magnetically collect SPRI beads and remove supernatant.",
    "First 180 uL ethanol wash on the magnet without mixing.",
    "Second 180 uL ethanol wash on the magnet without mixing.",
    "Clear residual ethanol and inspect bead drying.",
    "Elute the SPRI-purified libraries in 20 uL for five minutes.",
    "Magnetically separate the final libraries from SPRI beads.",
    "Move fresh output plate P4 from B4 to C2.",
    "Recover 18 uL per sample into the matched fresh output well.",
    "Collect libraries for QC and retain the sample/index run record.",
)


def add_parameters(parameters):
    parameters.add_int(
        variable_name="sample_count", display_name="Number of samples",
        description="Complete eight-well columns from 8 to 48 samples.",
        choices=[{"display_name": f"{n} samples", "value": n} for n in SAMPLE_COUNTS],
        default=DEFAULT_SAMPLE_COUNT,
    )
    parameters.add_bool(
        variable_name="dry_run", display_name="Water/dye dry run",
        description="Still moves and transfers all liquids; skips heating/cooling and shortens waits.",
        default=False,
    )


def build_run_plan(sample_count):
    """Map the sample wells, kit indexes and all source loads, tagged by the steps that use them."""
    if (isinstance(sample_count, bool) or not isinstance(sample_count, int)
            or sample_count not in SAMPLE_COUNTS):
        raise ValueError("sample_count must be one of 8, 16, 24, 32, 40, or 48.")
    columns = sample_count // SAMPLES_PER_COLUMN
    samples = []
    loads = {"cold": {}, "room": {}, "reservoir": {}}

    def add_source(zone, well, reagent, volume, reserve, section):
        entry = loads[zone].setdefault(
            well,
            {"reagent": reagent, "consume_ul": 0.0, "reserve_ul": reserve, "section": section},
        )
        if entry["reagent"] != reagent or entry["section"] != section:
            raise ValueError(f"Conflicting {section} reagent assignments at {zone}/{well}.")
        entry["consume_ul"] += volume

    for column in range(columns):
        for row_index, row in enumerate("ABCDEFGH"):
            number = column * 8 + row_index + 1
            well = f"{row}{column + 1}"
            # Physical-well exceptions take precedence over the regular row/column rule.
            i7, i5 = INDEX_EXCEPTIONS.get(well, (I7_BY_ROW[row_index], I5_BY_COLUMN[column]))
            sample = {
                "sample_number": number, "sample_name": f"S{number:02d}", "well": well,
                "input_well": well, "reactor_well": well, "pcr_well": well, "output_well": well,
                "i7": i7, "i5": i5, "index_pair": f"{i7}/{i5}",
                "index_exception": well in INDEX_EXCEPTIONS,
                "tag_source": f"{row}8", "pcr_source": f"{row}7", "silica_source": f"{row}7",
                "spri_source": f"{row}{8 + (column // 3)}",
                "silica_elution_source": well, "spri_elution_source": well,
                "sample_column": column + 1, "sample_row_index": row_index,
            }
            samples.append(sample)
            add_source("room", sample["silica_elution_source"], "DNA Purification Elution Buffer",
                       ELUTION_SOURCE_UL, ELUTION_RESERVE_UL, SECTION_B)

    # The TMM, PCR-premix and silica-bead source wells are re-aspirated once per run column.
    for row in "ABCDEFGH":
        add_source("cold", f"{row}8", "Prepared Tagmentation Master Mix (enzyme-free)", TMM_UL * columns,
                   round(TMM_UL * columns * TMM_RESERVE_FRACTION, 5), SECTION_A)
        add_source("cold", f"{row}7", "Prepared Universal PCR Premix", PCR_PREMIX_UL * columns,
                   PCR_RESERVE_UL, SECTION_B)
        add_source("room", f"{row}7", "Silica Beads", SILICA_BEADS_UL * columns, SILICA_RESERVE_UL, SECTION_A)

    for row in "ABCDEFGH":
        for source_column in (8, 9):
            uses = sum(sample["spri_source"] == f"{row}{source_column}" for sample in samples)
            if uses:
                add_source("room", f"{row}{source_column}", "SPRI Beads", SPRI_UL * uses,
                           SPRI_RESERVE_UL, SECTION_B)

    for well, reagent, volume, section in (
        ("A1", "Prepared DNA Binding Buffer", BINDING_BUFFER_UL * sample_count, SECTION_A),
        ("A2", "Prepared Silica Wash Buffer", SILICA_WASH_UL * sample_count, SECTION_B),
        ("A4", "Prepared Silica Wash Buffer", SILICA_WASH_UL * sample_count, SECTION_B),
        ("A3", "Fresh 80% Ethanol", ETHANOL_UL * sample_count, SECTION_B),
        ("A5", "Fresh 80% Ethanol", ETHANOL_UL * sample_count, SECTION_B),
    ):
        add_source("reservoir", well, reagent, volume, RESERVOIR_RESERVE_UL, section)

    for zone, entries in loads.items():
        capacity = 15000 if zone == "reservoir" else 200
        for entry in entries.values():
            entry["load_ul"] = round(entry["consume_ul"] + entry["reserve_ul"], 5)
            if entry["load_ul"] > capacity:
                raise ValueError(f"A reagent source exceeds {capacity} uL at {zone}.")
    if len({sample["index_pair"] for sample in samples}) != sample_count:
        raise ValueError("Every sample must carry a unique kit i7/i5 index pair.")
    return {"samples": samples, "loads": loads}


def run(protocol: protocol_api.ProtocolContext):
    sample_count = protocol.params.sample_count
    dry_run = protocol.params.dry_run
    run_plan = build_run_plan(sample_count)  # Reject invalid input before deck loading.
    samples = run_plan["samples"]
    columns = sample_count // SAMPLES_PER_COLUMN

    def step(number):
        index = number - FIRST_STEP
        if not 0 <= index < len(STEP_TITLES):
            raise ValueError(f"Step number {number} is outside this Step 1–26 protocol.")
        protocol.comment(f"Step {number}: {STEP_TITLES[index]}")

    def wait(seconds, reason):
        protocol.comment(f"INCUBATION: {reason}; normal duration {seconds} seconds.")
        protocol.delay(seconds=1 if dry_run else seconds)

    protocol.comment(
        f"RUN: Active Motif 53158 A2, {sample_count} samples in kit-plate wells A1:H{columns}, robot Steps 1–26 "
        f"in one run; {CELL_INPUT:,} fresh blood NK cells per active P1 well (inherited session input). "
        "Breakaway-plate fit and the Step 7 163 uL cold hold are user assumptions, not qualified.")
    mag = protocol.load_module("magneticBlockV1", "B2")
    temp = protocol.load_module("temperatureModuleV2", "C1")
    cold_adapter = temp.load_adapter("opentrons_96_well_aluminum_block", version=1)
    cold = cold_adapter.load_labware(PCR_PLATE, version=3, label="COLD reagent sources")
    hs = protocol.load_module("heaterShakerModuleV1", "D1")
    hs.load_adapter("opentrons_96_pcr_adapter", version=1)  # Physically installed; left idle.
    tc = protocol.load_module("thermocyclerModuleV2")
    tc.open_lid()
    chute = protocol.load_waste_chute()
    p50_racks = [protocol.load_labware("opentrons_flex_96_filtertiprack_50ul", P50_TIP_SLOT)]
    p1000_racks = [protocol.load_labware("opentrons_flex_96_filtertiprack_200ul", slot)
                   for slot in P1000_TIP_SLOTS]
    # Both pipettes stay in their default eight-nozzle ALL layout.
    p50 = protocol.load_instrument("flex_8channel_50", "right", tip_racks=p50_racks)
    p1000 = protocol.load_instrument("flex_8channel_1000", "left", tip_racks=p1000_racks)
    p3 = protocol.load_labware(PCR_PLATE, "A4", version=3, label="P3 clean PCR and SPRI plate")
    p4 = protocol.load_labware(PCR_PLATE, "B4", version=3, label="P4 fresh output")
    room = protocol.load_labware(PCR_PLATE, "B3", version=3, label="ROOM bead and elution sources")
    reservoir = protocol.load_labware("nest_12_reservoir_15ml", "C3", version=3)
    # P2 is seated on the open block at deck setup, before the run starts.
    p2 = tc.load_labware(KIT_PLATE_SURROGATE, version=3,
                         label="P2 pre-indexed Tn5 breakaway kit plate (Bio-Rad geometry surrogate)")
    p1 = protocol.load_labware(PCR_PLATE, WORKING_SLOT, version=3, label="P1 nuclei input")
    if not dry_run:
        temp.set_temperature(4)

    plates = {"cold": cold, "room": room, "reservoir": reservoir}
    source_remaining = {}
    source_reserve = {}
    drying_started = {}
    for zone, entries in run_plan["loads"].items():
        for name, entry in entries.items():
            # Every source for Steps 1–26 is loaded once before Step 1.
            liquid = protocol.define_liquid(entry["reagent"], "Prepared source; see loading guide", "#508AB8")
            well = plates[zone][name]
            well.load_liquid(liquid=liquid, volume=entry["load_ul"])
            source_remaining[well] = entry["load_ul"]
            source_reserve[well] = entry["reserve_ul"]
            protocol.comment(f"LOAD {zone}/{name}: {entry['reagent']}; {entry['load_ul']:g} uL "
                             f"({entry['consume_ul']:g} consumed + {entry['reserve_ul']:g} provisional reserve).")
    nuclei_liquid = protocol.define_liquid(
        "NK nuclei", f"Nuclei from {CELL_INPUT:,} fresh blood NK cells after manual preparation; "
        "assumed 10 uL residual", "#A360AA")
    tn5_liquid = protocol.define_liquid(
        "Pre-indexed Tn5", "4 uL indexed transposome supplied in each kit-plate well; not a shared source", "#D0A33A")
    for sample in samples:
        p1[sample["input_well"]].load_liquid(nuclei_liquid, NUCLEI_RESIDUAL_UL)
        p2[sample["reactor_well"]].load_liquid(tn5_liquid, TN5_UL)
    # P2 is already on the block: declare its real 4 uL enzyme volume, not an empty block,
    # and reach 4 C before the first transfer. 4 uL is below the published 10 uL minimum.
    if dry_run:
        protocol.comment("DRY RUN: initial 4 C Thermocycler cooling skipped.")
    else:
        tc.set_block_temperature(4, block_max_volume=TN5_UL)
        protocol.comment("COLD START: P2 held at the 4 C target with 4 uL enzyme per well, below the published "
                         "10 uL Thermocycler GEN2 minimum; this hold is not qualified.")
    protocol.pause(
        f"LOAD NOW — {sample_count} samples in wells A1:H{columns}, robot Steps 1–26 in one run. "
        + ("Pre-indexed kit plate P2 sits on the Thermocycler block, now at 4 C and held there. " if not dry_run
           else "Pre-indexed kit plate P2 sits on the Thermocycler block; water/dye mode skips the cooling. ")
        + "1) Load every C1/B3/C3 source in the loading table for this count; keep C1 at 4 C and B3/C3 at room "
        "temperature. 2) Just before resuming, take P1 "
        f"(nuclei from {CELL_INPUT:,} NK cells, 10 uL residual per active well) from cold storage and place it on "
        "C2; ambient wait time on C2 is not qualified. Full 200 uL racks at A2 and D2, a full 50 uL rack at A3, "
        "clean P3 at A4, fresh P4 at B4; B2, C4 and D4 empty; Heater-Shaker idle at D1. "
        "Resume immediately after placing P1."
    )

    # Tip ledger: one used-well set per physical rack, cleared only when that rack is
    # replaced. Every pickup is a complete column, taken from the rack with the fewest
    # unused columns (A2 before D2 on a tie), so a partly used rack is finished first.
    racks = {p50: list(p50_racks), p1000: list(p1000_racks)}
    used = {rack: set() for rack in (*p50_racks, *p1000_racks)}
    pending = {p50: 0, p1000: 0}  # Reserved pickups still to come; no refill until zero.

    def no_tips():
        if any(p.has_tip for p in (p50, p1000)):
            raise RuntimeError("Drop all tips before a plate move, manual pause or layout change.")

    def free_columns(rack):
        return [col for col in rack.columns() if all(w.well_name not in used[rack] for w in col)]

    def emptiest_first(pip):
        # Exhausted racks sort first, then partly used, then fresh; A2 (or A3) wins ties.
        return sorted(racks[pip], key=lambda rack: len(free_columns(rack)))

    def refill(pip, rack, reason=None):
        # Manual replacement of one named rack only; other racks keep their history.
        no_tips()
        protocol.home()
        unused = [col[0].well_name[1:] for col in free_columns(rack)]
        why = reason or f"the rack at {rack.parent} is used up"
        left = (f"{len(unused)} unused column{'s' if len(unused) > 1 else ''} ({', '.join(unused)})"
                if unused else "")
        protocol.pause(f"Replace the {rack.load_name} at {rack.parent} with a full rack. Why now: {why}. "
                       + (f"This run does not use its {left}; set those tips aside. " if unused else "")
                       + "Check seating, remove the rack lid, and inspect/empty the waste receptacle. "
                       "Resume only after replacement.")
        rack.reset()
        used[rack].clear()

    def reserve_tips(pip, count, purpose):
        # Before a protected block, check that its column pickups fit the pipette's
        # racks without a change; otherwise replace the emptiest rack first and say why.
        if pending[pip]:
            raise RuntimeError("A tip reservation is still open.")
        refilled = []
        while True:
            pool = sum(len(free_columns(rack)) for rack in racks[pip])
            if pool >= count:
                pending[pip] = count
                return
            candidates = [rack for rack in emptiest_first(pip) if rack not in refilled]
            if not candidates:
                raise RuntimeError("Requested uninterrupted block exceeds fresh tip racks.")
            holder = ("the P50 rack at A3 holds" if pip is p50
                      else f"the P1000 racks at {' and '.join(P1000_TIP_SLOTS)} hold")
            refill(pip, candidates[0], f"{count} uninterrupted column pickups are needed for {purpose}, "
                                       f"but {holder} only {pool} unused column{'' if pool == 1 else 's'}")
            refilled.append(candidates[0])

    def tip(pip):
        no_tips()
        if not any(free_columns(rack) for rack in racks[pip]):
            if pending[pip]:
                raise RuntimeError("A tip refill fell inside a reserved block.")
            refill(pip, emptiest_first(pip)[0])
        rack = min((r for r in racks[pip] if free_columns(r)), key=lambda r: len(free_columns(r)))
        column = free_columns(rack)[0]
        pip.pick_up_tip(column[0])
        used[rack].update(w.well_name for w in column)
        pending[pip] = max(pending[pip] - 1, 0)
        if pip.active_channels != SAMPLES_PER_COLUMN:
            raise RuntimeError("Unexpected active nozzle count.")

    def mode(pip, volume, slow=False):
        if pip.current_volume:
            raise RuntimeError("Volume mode can change only with an empty tip.")
        if pip is p50:
            pip.configure_for_volume(volume)
            pip.flow_rate.aspirate = 1.5 if volume <= 5 else 12
            pip.flow_rate.dispense = 2 if volume <= 5 else 15
            pip.flow_rate.blow_out = 15
        else:
            pip.flow_rate.aspirate = 5 if volume <= 5 else (25 if slow else 60)
            pip.flow_rate.dispense = 10 if volume <= 5 else (30 if slow else 80)
            pip.flow_rate.blow_out = 80
        if volume > pip.max_volume:
            raise ValueError("Transfer exceeds the configured pipette/tip capacity.")

    def lift(pip, well):
        # Slow withdrawal to 5 mm above the well on the API's collision-avoiding path.
        pip.move_to(well.top(z=5), speed=LIFT_SPEED_MM_S, force_direct=False)

    def consume(source_wells, volume):
        for source in source_wells:
            remaining = source_remaining[source] - volume
            if remaining < source_reserve[source] - 1e-6:
                raise RuntimeError(f"Insufficient planned source volume in {source}.")
            source_remaining[source] = remaining

    def aspiration_height(well, remaining_ul, preferred=1.0, immersion=0.25):
        # Use the native well-volume model to stay below the predicted final
        # meniscus. This is a geometric check, not a liquid-level measurement.
        surface = float(well.height_from_volume(remaining_ul))
        height = min(preferred, surface - immersion)
        if height < MIN_LIQUID_CLEARANCE_MM:
            raise ValueError(f"Insufficient modeled liquid depth in {well}: {remaining_ul:g} uL "
                             f"cannot support {immersion:g} mm immersion above the minimum clearance.")
        return height

    def mix(pip, well, volume, available_volume, repetitions=5):
        mode(pip, volume, slow=True)
        clearance = aspiration_height(well, available_volume - volume)
        aspirate_rate = 1.5 if pip is p50 and volume <= 5 else (12 if pip is p50 else 35)
        dispense_rate = 2 if pip is p50 and volume <= 5 else (15 if pip is p50 else 40)
        pip.mix(repetitions, volume, well.bottom(z=clearance),
                aspirate_flow_rate=aspirate_rate,
                dispense_flow_rate=dispense_rate,
                aspirate_delay=0.25, dispense_delay=0.25, final_push_out=0)
        lift(pip, well)

    def dispense_source(pip, volume, sources, destination, mix_volume=0, destination_volume=None,
                        premix=False, drop=True):
        # One row-matched source column (anchor first) to one destination column.
        if len(sources) != SAMPLES_PER_COLUMN:
            raise ValueError("Every source group is one complete column of eight wells.")
        source = sources[0]
        tip(pip)
        if premix:
            available = min(source_remaining[well] for well in sources)
            reserve = max(source_reserve[well] for well in sources)
            mix_volume_source = min(30 if pip is p50 else 100, available - reserve)
            mix(pip, source, mix_volume_source, available_volume=available, repetitions=5)
        mode(pip, volume, slow=True)
        source_height = aspiration_height(
            source, source_remaining[source] - volume, SOURCE_CLEARANCE_MM)
        pip.aspirate(volume, source.bottom(z=source_height))
        consume(sources, volume)
        lift(pip, source)
        pip.dispense(volume, destination.bottom(z=1.0), push_out=0)
        lift(pip, destination)
        if mix_volume:
            if destination_volume is None:
                raise ValueError("Mixing needs the explicit nominal destination volume.")
            mix(pip, destination, mix_volume, available_volume=destination_volume)
        if drop:
            pip.drop_tip(chute)

    def groups():
        # Complete eight-sample columns only; build_run_plan rejects any other count.
        return [samples[col * 8:(col + 1) * 8] for col in range(columns)]

    def move(plate, destination):
        no_tips()
        if destination == tc or plate.parent == tc:
            tc.open_lid()
        protocol.move_labware(plate, destination, use_gripper=True)

    def remove_bulk(plate, per_well, remaining_ul=5.0):
        for group in groups():
            tip(p1000)
            mode(p1000, per_well, slow=True)
            well = plate[group[0]["well"]]
            clearance = aspiration_height(well, remaining_ul, BULK_CLEARANCE_MM,
                                           immersion=0.15 if plate == p2 else 0.25)
            p1000.aspirate(per_well, well.bottom(z=clearance))
            lift(p1000, well)
            p1000.dispense(per_well, chute)
            p1000.drop_tip(chute)

    def remove_residual(plate, volume, clearance):
        # The P50 with fresh 50 uL tips removes the small residual. It may aspirate
        # air; the following operator inspection must establish a dry endpoint, and
        # neither bead clearance nor the recovered volume is measured here.
        for group in groups():
            tip(p50)
            mode(p50, volume, slow=True)
            well = plate[group[0]["well"]]
            p50.aspirate(volume, well.bottom(z=clearance))
            lift(p50, well)
            p50.dispense(volume, chute)
            p50.drop_tip(chute)
            for sample in group:
                drying_started[(plate, sample["well"])] = time.monotonic()

    def wash_add(plate, source, volume, air_gap):
        for group in groups():
            tip(p1000)
            destination = plate[group[0]["well"]]
            mode(p1000, volume)
            source_height = aspiration_height(source, source_remaining[source] - volume * len(group))
            p1000.aspirate(volume, source.bottom(z=source_height))
            consume([source], volume * len(group))
            lift(p1000, source)
            if air_gap:
                p1000.air_gap(air_gap, in_place=True)
            p1000.dispense(volume + air_gap, destination.top(z=-1))
            lift(p1000, destination)
            p1000.drop_tip(chute)

    def silica_wash(step_number, source_well, prepare_final=False):
        wash_add(p2, reservoir[source_well], SILICA_WASH_UL, air_gap=0)
        # The wash now covers the beads, so the mixing tips are not reserved: they may
        # finish a partly used rack, and any rack change here happens with beads wet.
        move(p2, WORKING_SLOT)
        for group in groups():
            tip(p1000)
            mix(p1000, p2[group[0]["well"]], 120, available_volume=SILICA_WASH_UL + 5)
            p1000.drop_tip(chute)
        move(p2, mag)
        wait(30, "silica wash collection")
        # Reserve while the wash still covers the silica beads.
        if prepare_final:
            # P1000 for the wash removal; P50 for the residual removal and the eluate
            # addition, so no rack change occurs until every well is wet again.
            reserve_tips(p1000, columns, f"the Step {step_number} wash removal")
            reserve_tips(p50, 2 * columns,
                         f"the Step {step_number + 1} residual removal and Step {step_number + 2} eluate addition")
        else:
            reserve_tips(p1000, 2 * columns,
                         f"the Step {step_number} wash removal and Step {step_number + 1} wash addition")
        remove_bulk(p2, SILICA_WASH_UL)

    def elute(plate, key, volume, mix_volume):
        # Rehydrate every pellet before mixing any well. The last column keeps its
        # addition tips to mix that same column.
        elution_groups = groups()
        for index, group in enumerate(elution_groups):
            tip(p50)
            mode(p50, volume, slow=True)
            source_wells = [room[s[key]] for s in group]
            source = source_wells[0]
            target = plate[group[0]["well"]]
            source_height = aspiration_height(source, source_remaining[source] - volume)
            p50.aspirate(volume, source.bottom(z=source_height))
            consume(source_wells, volume)
            lift(p50, source)
            p50.dispense(volume, target.bottom(z=1), push_out=0)
            lift(p50, target)
            now = time.monotonic()  # Buffer added: the dry interval ends here, before any mixing.
            for sample in group:
                began = drying_started[(plate, sample["well"])]
                protocol.comment(f"DRY INTERVAL {plate.name}/{sample['well']}: {now - began:.1f} s "
                                 "from residual-removal completion to buffer addition; command elapsed time, not measured bead dryness.")
            if index < len(elution_groups) - 1:
                p50.drop_tip(chute)
        # Every well is wet. Mix the last column with its own attached tips, then
        # the other columns with fresh tips; any rack change comes after the drop.
        mix(p50, plate[elution_groups[-1][0]["well"]], mix_volume, available_volume=volume)
        p50.drop_tip(chute)
        for group in elution_groups[:-1]:
            tip(p50)
            mix(p50, plate[group[0]["well"]], mix_volume, available_volume=volume)
            p50.drop_tip(chute)

    step(1)
    # Secure the Step 5 P1000 pass before any nuclei meet Tn5; both 200 uL racks start full.
    reserve_tips(p1000, 2 * columns - 1, "the Step 5 binding-buffer additions and mixes")
    reserve_tips(p50, columns, "the Step 1 TMM additions and nuclei transfers")
    for group in groups():
        anchor = group[0]["well"]
        # Fresh P50 column: 21 uL enzyme-free TMM into P1, mix 5 x 20 uL in the nominal 31 uL.
        dispense_source(p50, TMM_UL, [cold[s["tag_source"]] for s in group], p1[anchor],
                        mix_volume=20, destination_volume=INPUT_MIX_UL, drop=False)
        # Same tips: aspirate the whole nominal 31 uL slowly from 0.5 mm and dispense it
        # onto the matched P2 well's own 4 uL pre-indexed Tn5; Tn5 is never pooled or moved.
        mode(p50, INPUT_MIX_UL, slow=True)
        p50.flow_rate.aspirate = TRANSFER_RATE_UL_S
        p50.aspirate(INPUT_MIX_UL, p1[anchor].bottom(z=LOW_CLEARANCE_MM))
        lift(p50, p1[anchor])
        p50.dispense(INPUT_MIX_UL, p2[anchor].bottom(z=1.0), push_out=0)
        lift(p50, p2[anchor])
        mix(p50, p2[anchor], 20, available_volume=TAG_REACTION_UL)
        p50.drop_tip(chute)  # Dropped before any next source.
        protocol.comment(f"TAG START {[s['well'] for s in group]}: nominal 31 uL nuclei + TMM combined with "
                         "each well's pre-indexed Tn5 in P2 (35 uL nominal).")
    if protocol.deck[P1_PARK_SLOT] is not None:
        raise RuntimeError("D4 must be empty to park P1.")
    move(p1, P1_PARK_SLOT)  # Frees C2; P2 stays on the Thermocycler at the 4 C target.
    step(2)
    no_tips()
    protocol.pause("Confirm the reusable Thermocycler seal is seated on the lid, then resume to close the module.")
    tc.close_lid()
    step(3)
    if dry_run:
        wait(1800, "static tagmentation at 37 C; the water/dye mode shortens this wait")
    else:
        tc.set_lid_temperature(37)
        tc.set_block_temperature(37, hold_time_minutes=30, block_max_volume=TAG_REACTION_UL)
    tag_start_time = time.monotonic()
    step(4)
    tc.open_lid()
    tc.deactivate_lid()
    step(5)
    # Add binding buffer to every P2 column before mixing any column, preserving a short
    # and consistent quench; the last column keeps its addition tips to mix itself.
    binding_groups = groups()
    for index, group in enumerate(binding_groups):
        tip(p1000)
        mode(p1000, BINDING_BUFFER_UL)
        binding_source = reservoir["A1"]
        source_height = aspiration_height(
            binding_source, source_remaining[binding_source] - BINDING_BUFFER_UL * len(group))
        p1000.aspirate(BINDING_BUFFER_UL, binding_source.bottom(z=source_height))
        consume([binding_source], BINDING_BUFFER_UL * len(group))
        lift(p1000, binding_source)
        p2_anchor = p2[group[0]["well"]]
        p1000.dispense(BINDING_BUFFER_UL, p2_anchor.bottom(z=1), push_out=0)
        lift(p1000, p2_anchor)
        protocol.comment(
            f"TAG STOP {[sample['well'] for sample in group]}: binding buffer added "
            f"{time.monotonic() - tag_start_time:.1f} seconds after static incubation completed."
        )
        if index < len(binding_groups) - 1:
            p1000.drop_tip(chute)
    mix(p1000, p2[binding_groups[-1][0]["well"]], 100, available_volume=BOUND_REACTION_UL)
    p1000.drop_tip(chute)
    for group in binding_groups[:-1]:
        tip(p1000)
        mix(p1000, p2[group[0]["well"]], 100, available_volume=BOUND_REACTION_UL)
        p1000.drop_tip(chute)

    step(6)
    reserve_tips(p50, columns, "the Step 6 silica-bead additions")
    for group in groups():
        dispense_source(
            p50, SILICA_BEADS_UL, [room[s["silica_source"]] for s in group], p2[group[0]["well"]],
            mix_volume=30, destination_volume=BOUND_REACTION_UL + SILICA_BEADS_UL, premix=True,
        )

    no_tips()
    # Mid-run budget: Steps 1–6 sources are at reserve; Steps 8–26 sources are untouched.
    for zone, entries in run_plan["loads"].items():
        for source_name, entry in entries.items():
            left = source_remaining[plates[zone][source_name]]
            if entry["section"] == SECTION_A:
                if abs(left - entry["reserve_ul"]) > 1e-6:
                    raise RuntimeError(f"Steps 1–6 source budget mismatch at {zone}/{source_name}.")
            elif abs(left - entry["load_ul"]) > 1e-6:
                raise RuntimeError(f"A Steps 8–26 source was used before Step 7 at {zone}/{source_name}.")

    step(7)
    # Whole-plate moves only. Park P2 at C2 so the block is truly empty, pre-cool it while
    # declaring that real state (0 uL), then return P2. No block command is issued while
    # P2 holds the 163 uL bound reaction.
    if protocol.deck[WORKING_SLOT] is not None:
        raise RuntimeError("C2 must be empty to park P2 during the pre-cool.")
    tc.open_lid()
    protocol.move_labware(p2, WORKING_SLOT, use_gripper=True)
    if tc.labware is not None:
        raise RuntimeError("The Thermocycler block must be empty before the 4 C pre-cool.")
    if dry_run:
        protocol.comment("DRY RUN: 4 C pre-cool of the empty block skipped.")
    else:
        tc.set_block_temperature(4, block_max_volume=0)  # Returns once the empty block reaches 4 C.
    protocol.move_labware(p2, tc, use_gripper=True)
    tc.close_lid()
    protocol.comment("COLD HOLD: P2 holds 163 uL nominal per well, above the published 10–100 uL Thermocycler GEN2 "
                     "range, in a breakaway kit plate modelled by a Bio-Rad geometry surrogate. This hold is not "
                     "qualified for this assay or plate; liquid temperature is not measured.")
    wait(300, "five-minute hold of P2 on the 4 C block")
    tc.open_lid()
    protocol.move_labware(p2, mag, use_gripper=True)
    wait(300, "magnetic collection of silica beads on B2")

    step(8)
    # Reserve while the binding mix still covers the beads.
    reserve_tips(p1000, 2 * columns, "the Step 8 binding removal and Step 9 wash addition")
    remove_bulk(p2, BOUND_REACTION_UL + SILICA_BEADS_UL - 5)  # 163 uL nominal; leave 5 uL.
    step(9)
    silica_wash(9, "A2")
    step(10)
    silica_wash(10, "A4", prepare_final=True)
    step(11)
    remove_residual(p2, 5, LOW_CLEARANCE_MM)
    no_tips()
    protocol.pause("Inspect P2 silica beads on B2. Allow the remaining wash to evaporate, approximately 2 minutes, "
                   "until beads are no longer shiny; do not let them crack. Account for the earliest-processed well, "
                   "not only the last. Resume promptly when ready to elute.")
    step(12)
    move(p2, WORKING_SLOT)
    elute(p2, "silica_elution_source", SILICA_ELUTION_UL, 25)
    wait(300, "silica DNA elution at room temperature")
    step(13)
    move(p2, mag)
    wait(300, "silica separation before PCR")
    move(p3, tc)  # A4 to the empty Thermocycler block, still at its 4 C target.
    reserve_tips(p50, columns + 1, "the Step 13 PCR premix precharge and DNA transfers")
    # One fresh P50 column precharges every EMPTY P3 column with the common universal
    # premix (Q5 buffer, dNTP, enzyme, P5/P7) before any DNA is in P3. These tips touch
    # only the premix source and identical premix, never DNA, and are dropped afterwards.
    tip(p50)
    mode(p50, PCR_PREMIX_UL, slow=True)
    for group in groups():
        premix_sources = [cold[s["pcr_source"]] for s in group]
        premix_source = premix_sources[0]
        source_height = aspiration_height(
            premix_source, source_remaining[premix_source] - PCR_PREMIX_UL, SOURCE_CLEARANCE_MM)
        p50.aspirate(PCR_PREMIX_UL, premix_source.bottom(z=source_height))
        consume(premix_sources, PCR_PREMIX_UL)
        lift(p50, premix_source)
        precharge_target = p3[group[0]["well"]]
        p50.dispense(PCR_PREMIX_UL, precharge_target.bottom(z=1.0), push_out=0)
        lift(p50, precharge_target)
    p50.drop_tip(chute)
    for group in groups():
        # Fresh tips per DNA column: transfer into the precharged well, mix, drop.
        tip(p50)
        mode(p50, PCR_INPUT_UL, slow=True)
        anchor = group[0]["well"]
        source = p2[anchor]
        # 35 uL eluate minus 33.5 uL leaves 1.5 uL nominal: low modeled height, slow aspiration.
        clearance = aspiration_height(source, SILICA_ELUTION_UL - PCR_INPUT_UL, immersion=0.15)
        p50.flow_rate.aspirate = TRANSFER_RATE_UL_S
        p50.aspirate(PCR_INPUT_UL, source.bottom(z=clearance))
        lift(p50, source)
        p50.dispense(PCR_INPUT_UL, p3[anchor].bottom(z=1), push_out=0)
        lift(p50, p3[anchor])
        mix(p50, p3[anchor], 35, available_volume=PCR_REACTION_UL)
        p50.drop_tip(chute)
    step(14)
    move(p2, "A4")  # A4 is free once P3 has moved to the Thermocycler.
    step(15)
    # Automated checkpoint, no liquid handling: the premix source is at reserve, so every
    # active P3 well holds 16.5 uL premix + 33.5 uL DNA = 50 uL nominal.
    no_tips()
    for row in "ABCDEFGH":
        premix_well = cold[f"{row}7"]
        if abs(source_remaining[premix_well] - source_reserve[premix_well]) > 1e-6:
            raise RuntimeError(f"Universal PCR premix at C1/{row}7 is not at its reserve after Step 13.")
    protocol.comment(f"PCR CHECK: {sample_count} reactions in P3 at {PCR_REACTION_UL:g} uL nominal "
                     f"({PCR_PREMIX_UL:g} uL premix + {PCR_INPUT_UL:g} uL DNA); premix source at reserve.")
    step(16)
    no_tips()
    tc.close_lid()
    if not dry_run:
        tc.set_lid_temperature(105)
        tc.set_block_temperature(72, hold_time_minutes=5, block_max_volume=PCR_REACTION_UL)
        tc.set_block_temperature(98, hold_time_seconds=30, block_max_volume=PCR_REACTION_UL)
        tc.execute_profile(steps=[
            {"temperature": 98, "hold_time_seconds": 10},
            {"temperature": 63, "hold_time_seconds": 30},
            {"temperature": 72, "hold_time_seconds": 60},
        ], repetitions=10, block_max_volume=PCR_REACTION_UL)
        tc.set_block_temperature(10, block_max_volume=PCR_REACTION_UL)
    tc.open_lid()
    tc.deactivate()
    step(17)
    move(p3, WORKING_SLOT)
    for group in groups():
        dispense_source(p1000, SPRI_UL, [room[s["spri_source"]] for s in group], p3[group[0]["well"]],
                        mix_volume=80, destination_volume=PCR_REACTION_UL + SPRI_UL, premix=True)
    wait(300, "SPRI binding at room temperature")
    step(18)
    move(p3, mag)
    wait(300, "SPRI bead collection")
    # Each protected interval uses at most 2 x 48 tips on either instrument.
    reserve_tips(p1000, 2 * columns, "the Step 18 supernatant removal and Step 19 ethanol addition")
    remove_bulk(p3, PCR_REACTION_UL + SPRI_UL - 5)  # 110 uL mixture, leaving 5 uL.
    step(19)
    wash_add(p3, reservoir["A3"], ETHANOL_UL, air_gap=5)
    wait(30, "first SPRI ethanol wash; no mixing on magnet")
    reserve_tips(p1000, 2 * columns, "the Step 19 ethanol removal and Step 20 ethanol addition")
    remove_bulk(p3, ETHANOL_UL)
    step(20)
    wash_add(p3, reservoir["A5"], ETHANOL_UL, air_gap=5)
    wait(30, "second SPRI ethanol wash; no mixing on magnet")
    reserve_tips(p1000, columns, "the Step 20 ethanol removal")
    reserve_tips(p50, 2 * columns, "the Step 21 residual removal and Step 22 eluate addition")
    remove_bulk(p3, ETHANOL_UL)
    step(21)
    remove_residual(p3, 5, LOW_CLEARANCE_MM)
    no_tips()
    protocol.pause("Inspect the P3 SPRI beads on B2. Allow residual ethanol to evaporate until matte, normally "
                   "2–5 minutes including time spent clearing the first wells. Resume promptly before the beads crack. "
                   "P4 is already staged at B4.")
    step(22)
    move(p3, WORKING_SLOT)
    elute(p3, "spri_elution_source", FINAL_ELUTION_UL, 15)
    wait(300, "final library elution at room temperature")
    step(23)
    move(p3, mag)
    wait(300, "final SPRI separation")
    step(24)
    move(p4, WORKING_SLOT)
    step(25)
    for group in groups():
        tip(p50)
        mode(p50, FINAL_RECOVERY_UL, slow=True)
        anchor = group[0]["well"]
        source = p3[anchor]
        p50.flow_rate.aspirate = TRANSFER_RATE_UL_S
        p50.aspirate(FINAL_RECOVERY_UL, source.bottom(z=LOW_CLEARANCE_MM))
        lift(p50, source)
        p50.dispense(FINAL_RECOVERY_UL, p4[anchor].bottom(z=1), push_out=0)
        lift(p50, p4[anchor])
        p50.drop_tip(chute)
    step(26)
    no_tips()
    protocol.comment(f"FINISHED: {sample_count} libraries in P4 at {WORKING_SLOT}; programmed recovery "
                     f"{FINAL_RECOVERY_UL:g} uL from {FINAL_ELUTION_UL:g} uL elution. Keep the sample/kit-index map. "
                     "Quantify and inspect fragment profiles; successful simulation is not wet ATAC validation.")
    # Every source, early (Steps 1–6) and late (Steps 8–26), must end at its reserve.
    for zone, entries in run_plan["loads"].items():
        for name, entry in entries.items():
            left = source_remaining[plates[zone][name]]
            if abs(left - entry["reserve_ul"]) > 1e-6:
                raise RuntimeError(f"Source budget mismatch at {zone}/{name}: {left} uL remains.")
