"""Active Motif 53157 A1 on Flex; supervised development protocol, API 2.27.

Fresh blood NK cells, 100,000 cells/sample, 1–16 samples. The operator leaves
10 uL around each nuclei pellet. Manual centrifugation, ice, seals, drying
inspection and consumable exchanges remain. No physical qualification is claimed.
Read ATAC_Seq_Express_Flex_steps.md and the source-loading CSV before use.
"""

import time

from opentrons import protocol_api
from opentrons.protocol_api import ALL, SINGLE, OFF_DECK
from opentrons.types import Point


metadata = {
    "protocolName": "ATAC-Seq Express — Flex — fresh blood NK — 1–16 samples",
    "author": "Andres / protocol adaptation",
    "description": "Active Motif 53157 A1 with supervised manual handoffs; 10 uL nuclei residual.",
    "apiLevel": "2.27",
}
requirements = {"robotType": "Flex"}

PCR_PLATE = "biorad_96_wellplate_200ul_pcr"
DEEP_PLATE = "nest_96_wellplate_2ml_deep"
WORKING_SLOT = "C2"
P1000_TIP_SLOT = "A2"
CELL_INPUT = 100000
NUCLEI_RESIDUAL_UL = 10.0
TAG_MIX_UL = 25.0
TAG_REACTION_UL = NUCLEI_RESIDUAL_UL + TAG_MIX_UL
BINDING_BUFFER_UL = 125.0
BOUND_TRANSFER_UL = TAG_REACTION_UL + BINDING_BUFFER_UL
SILICA_ELUTION_UL = 40.0  # User-selected change from the manual's 35 uL.
FINAL_RECOVERY_UL = 18.0  # 20 uL elution; leave 2 uL to reduce bead carryover.

# 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
PCR_RESIDUAL_CLEARANCE_MM = 0.5
DEEP_RESIDUAL_CLEARANCE_MM = 0.3
SOURCE_RESERVE_UL = 10.0
PRIMER_RESERVE_UL = 2.0
SILICA_RESERVE_UL = 4.0
RESERVOIR_RESERVE_UL = 1000.0

STEP_TITLES = (
    "Validate the run, configure the deck and cool the modules.",
    "Load counted, pelleted NK cells and the prepared reagents.",
    "Add 100 uL cold PBS without resuspending the cell pellets.",
    "Manual cold PBS-wash spin and careful supernatant removal.",
    "Add 100 uL cold lysis buffer and gently resuspend the cells.",
    "Manual nuclei spin; retain 10 uL and return promptly.",
    "Add 25 uL tagmentation mix and gently resuspend nuclei.",
    "Manually seal the tagmentation plate for shaking.",
    "Incubate at 37 C and 800 rpm for 30 minutes.",
    "Stop shaking, manually unseal P1 and return it to the Thermocycler.",
    "Add 125 uL binding buffer on the Thermocycler and transfer each nominal 160 uL reaction to P3.",
    "Add 3 uL silica beads and mix the binding reactions.",
    "Manual five-minute ice incubation; remove used P1.",
    "Magnetically collect silica beads and remove binding supernatant.",
    "First 200 uL silica wash with off-magnet resuspension.",
    "Second 200 uL silica wash with off-magnet resuspension.",
    "Clear residual silica wash and inspect bead drying.",
    "Elute silica-purified DNA in the selected 40 uL for five minutes.",
    "Separate silica beads and transfer 33.5 uL to clean PCR plate P2.",
    "Stage the used silica plate P3 at A4.",
    "Add the assigned i7/i5 primers and common PCR mix.",
    "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, inspect drying and load fresh output plate P4.",
    "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 A4 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="Fresh blood NK samples, including assigned controls; active wells only.",
        default=1, minimum=1, maximum=16,
    )
    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):
    """Explicit sample/index identity and source loads, shared with the run guide."""
    if isinstance(sample_count, bool) or not isinstance(sample_count, int) or not 1 <= sample_count <= 16:
        raise ValueError("sample_count must be an integer from 1 to 16.")
    wells = [f"{row}{column}" for column in (1, 2) for row in "ABCDEFGH"][:sample_count]
    samples = []
    loads = {"cold": {}, "room": {}, "reservoir": {}}

    def add_source(zone, well, reagent, volume, reserve):
        entry = loads[zone].setdefault(well, {"reagent": reagent, "consume_ul": 0.0, "reserve_ul": reserve})
        if entry["reagent"] != reagent:
            raise ValueError(f"Two reagents assigned to {zone}/{well}.")
        entry["consume_ul"] += volume

    for i, well in enumerate(wells):
        # Latin-square order balances primer use as the run grows, while keeping
        # all sixteen i7/i5 pairs distinct. IDs are kit IDs, not 10X index IDs.
        i7_number = i % 4
        i5_number = (i % 4 + i // 4) % 4
        sample = {
            "sample_number": i + 1, "well": well,
            "i7": f"N70{i7_number + 1}", "i5": f"N50{i5_number + 1}",
            "pbs_source": well,
            "lysis_source": f"{well[0]}{int(well[1:]) + 2}",
            "tag_source": f"{'ABC'[i // 7]}5",
            "pcr_mix_source": "A6" if i < 15 else "B6",
            "i7_source": f"A{7 + i7_number}",
            "i5_source": f"B{7 + i5_number}",
            "spri_source": f"A{1 + i // 3}",
            "silica_elution_source": f"{well[0]}{int(well[1:]) + 7}",
            "spri_elution_source": f"{well[0]}{int(well[1:]) + 7}",
        }
        samples.append(sample)
        for key, reagent, volume, reserve in (
            ("pbs_source", "Cold 1x PBS", 100.0, 20.0),
            ("lysis_source", "Cold ATAC Lysis Buffer", 100.0, 20.0),
            ("tag_source", "Prepared Tagmentation Master Mix", TAG_MIX_UL, SOURCE_RESERVE_UL),
            ("pcr_mix_source", "Prepared PCR Common Mix", 11.5, SOURCE_RESERVE_UL),
            ("i7_source", sample["i7"], 2.5, PRIMER_RESERVE_UL),
            ("i5_source", sample["i5"], 2.5, PRIMER_RESERVE_UL),
        ):
            add_source("cold", sample[key], reagent, volume, reserve)
        add_source("room", sample["spri_source"], "SPRI Beads", 60.0, SOURCE_RESERVE_UL)
        # Matched source columns enable parallel rehydration after drying.
        add_source("room", sample["silica_elution_source"], "DNA Purification Elution Buffer",
                   SILICA_ELUTION_UL + 20.0, 5.0)

    add_source("room", "A7", "Silica Beads", 3.0 * sample_count, SILICA_RESERVE_UL)
    for well, reagent, volume in (
        ("A1", "Prepared DNA Binding Buffer", BINDING_BUFFER_UL * sample_count),
        ("A2", "Prepared Silica Wash Buffer", 400.0 * sample_count),
        ("A3", "Fresh 80% Ethanol", 360.0 * sample_count),
    ):
        add_source("reservoir", well, reagent, volume, RESERVOIR_RESERVE_UL)
    for zone, entries in loads.items():
        for entry in entries.values():
            entry["load_ul"] = entry["consume_ul"] + entry["reserve_ul"]
            if entry["load_ul"] > (15000 if zone == "reservoir" else 200):
                raise ValueError("A reagent source exceeds its defined well capacity.")
    if len({(s["i7"], s["i5"]) for s in samples}) != sample_count:
        raise ValueError("Duplicate index pairs.")
    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"]

    def step(number):
        protocol.comment(f"Step {number}: {STEP_TITLES[number - 1]}")

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

    step(1)
    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_adapter = hs.load_adapter("opentrons_96_pcr_adapter", version=1)
    tc = protocol.load_module("thermocyclerModuleV2")
    tc.open_lid()
    hs.close_labware_latch()
    chute = protocol.load_waste_chute()
    rack50 = protocol.load_labware("opentrons_flex_96_filtertiprack_50ul", "A3")
    rack200 = protocol.load_labware("opentrons_flex_96_filtertiprack_200ul", P1000_TIP_SLOT)
    p50 = protocol.load_instrument("flex_8channel_50", "right", tip_racks=[rack50])
    p1000 = protocol.load_instrument("flex_8channel_1000", "left", tip_racks=[rack200])
    p1 = tc.load_labware(PCR_PLATE, version=3, label="P1 cells and tagmentation")
    p2 = protocol.load_labware(PCR_PLATE, "A4", version=3, label="P2 clean PCR and SPRI")
    p3 = protocol.load_labware(DEEP_PLATE, WORKING_SLOT, version=5, label="P3 silica cleanup")
    p4 = protocol.load_labware(PCR_PLATE, OFF_DECK, 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)
    for pip in (p50, p1000):
        pip.configure_nozzle_layout(style=SINGLE, start="A1", tip_racks=pip.tip_racks)
        pip.default_speed = 100
    if not dry_run:
        temp.set_temperature(4)
        tc.set_block_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():
            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).")
    sample_liquid = protocol.define_liquid("NK sample", "100,000 fresh blood NK cells; operator-confirmed residual", "#A360AA")
    for sample in samples:
        p1[sample["well"]].load_liquid(sample_liquid, NUCLEI_RESIDUAL_UL)
        protocol.comment(f"SAMPLE {sample['sample_number']}: {sample['well']} on P1/P2/P3/P4; "
                         f"i7={sample['i7']}, i5={sample['i5']}; input={CELL_INPUT} cells.")

    # Preserve intact columns for ALL by exhausting each single-tip column
    # from front to back. Inspect for adjacent tips clinging to inactive nozzles.
    racks = {p50: rack50, p1000: rack200}
    used = {p50: set(), p1000: set()}
    layouts = {p50: 1, p1000: 1}

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

    def refill(pip):
        no_tips()
        protocol.home()
        protocol.pause(f"Replace the complete {racks[pip].load_name} at {racks[pip].parent} with a fresh rack. "
                       "Check seating, remove the rack lid, and inspect/empty the waste receptacle. Resume only after replacement.")
        pip.reset_tipracks()
        used[pip].clear()

    def next_tips(pip, channels, taken):
        if channels == 8:
            return next((col for col in racks[pip].columns()
                         if all(w.well_name not in taken for w in col)), None)
        ordered = [well for column in racks[pip].columns() for well in reversed(column)]
        well = next((w for w in ordered if w.well_name not in taken), None)
        return [well] if well is not None else None

    def reserve_tips(pip, upcoming_layouts):
        # Evaluate the actual pickup order before a time-critical block starts.
        for attempt in range(2):
            taken = set(used[pip])
            for channels in upcoming_layouts:
                future = next_tips(pip, channels, taken)
                if future is None:
                    break
                taken.update(w.well_name for w in future)
            else:
                return
            if attempt == 0:
                refill(pip)
        raise RuntimeError("Requested uninterrupted block exceeds one fresh tip rack.")

    def tip(pip, channels=1):
        no_tips()
        if layouts[pip] != channels:
            if channels == 8:
                pip.configure_nozzle_layout(style=ALL, tip_racks=[racks[pip]])
            elif channels == 1:
                pip.configure_nozzle_layout(style=SINGLE, start="A1", tip_racks=[racks[pip]])
            else:
                raise ValueError("This version uses full columns or explicit SINGLE tails only.")
            layouts[pip] = channels
        wells = next_tips(pip, channels, used[pip])
        if wells is None:
            refill(pip)
            wells = next_tips(pip, channels, used[pip])
        pip.pick_up_tip(wells[0])
        used[pip].update(w.well_name for w in wells)
        if pip.active_channels != channels:
            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 position(pip, well, z):
        # Rear SINGLE nozzle at a rear reservoir pickup keeps the inactive bank
        # away from the front D3 chute. Never recenter an air gap or lift here.
        # ALL uses the reservoir's centerMultichannelOnWells quirk; adding the
        # SINGLE offset to ALL would move the centred eight-tip array too far.
        y = 30.0 if well.parent == reservoir and pip.active_channels == 1 else 0.0
        return well.bottom(z=z).move(Point(y=y))

    def lift(pip, well):
        y = 30.0 if well.parent == reservoir and pip.active_channels == 1 else 0.0
        pip.move_to(well.top(z=5).move(Point(y=y)))

    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, position(pip, well, 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, source, destination, mix_volume=0, destination_volume=None, premix=False):
        tip(pip)
        if premix:
            mix_volume_source = min(30 if pip is p50 else 100, source_remaining[source] - source_reserve[source])
            mix(pip, source, mix_volume_source, available_volume=source_remaining[source], repetitions=5)
        mode(pip, volume, slow=True)
        source_height = aspiration_height(source, source_remaining[source] - volume, SOURCE_CLEARANCE_MM)
        pip.aspirate(volume, position(pip, source, source_height))
        consume([source], 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)
        pip.drop_tip(chute)

    def groups():
        result = []
        full_count = sample_count // 8
        for col in range(full_count):
            result.append(samples[col * 8:(col + 1) * 8])
        result.extend([sample] for sample in samples[full_count * 8:])
        return result

    def cold_add(key, destination_plate, mix_volume=0):
        for group in groups():
            tip(p1000, len(group))
            mode(p1000, 100, slow=True)
            source_wells = [cold[s[key]] for s in group]
            destination = destination_plate[group[0]["well"]]
            source_height = aspiration_height(source_wells[0], source_remaining[source_wells[0]] - 100)
            p1000.aspirate(100, position(p1000, source_wells[0], source_height))
            consume(source_wells, 100)
            lift(p1000, source_wells[0])
            # Slow, near-wall PBS delivery avoids directing a jet at the pellet.
            target = destination.top(z=-2).move(Point(x=1.0)) if not mix_volume else destination.bottom(z=1)
            p1000.dispense(100, target, push_out=0)
            lift(p1000, destination)
            if mix_volume:
                mix(p1000, destination, mix_volume, available_volume=110)
            p1000.drop_tip(chute)

    def move(plate, destination):
        no_tips()
        if destination == tc or plate.parent == tc:
            tc.open_lid()
        if destination == hs_adapter or plate.parent == hs_adapter:
            # The unsealing handoff already stops and opens D1. Reissuing a
            # stop command with an open latch is forbidden by the module API.
            if hs.current_speed:
                if hs.labware_latch_status != "idle_closed":
                    raise RuntimeError("The Heater-Shaker must be latched before stopping active shaking.")
                hs.deactivate_shaker()
            if hs.labware_latch_status != "idle_open":
                hs.open_labware_latch()
        protocol.move_labware(plate, destination, use_gripper=True)
        if destination == hs_adapter:
            hs.close_labware_latch()

    def cold_spin(message):
        no_tips()
        protocol.comment(message)
        tc.open_lid()
        protocol.move_labware(p1, OFF_DECK, use_gripper=False)
        protocol.comment(message + " Return P1 unsealed, A1 at the back-left; confirm only after the spin and aspiration are finished.")
        protocol.move_labware(p1, tc, use_gripper=False)
        # The operator, not the robot, has removed the supernatant.
        for sample in samples:
            p1[sample["well"]].load_liquid(sample_liquid, NUCLEI_RESIDUAL_UL)
        protocol.comment("MANUAL VOLUME: P1 now has 10 uL liquid per active well; operator confirmation, not a measured value.")

    def remove_bulk(plate, per_well, remaining_ul=5.0):
        for group in groups():
            tip(p1000, len(group))
            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 == p3 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):
        # Residual removal may aspirate air. The following operator inspection
        # must establish a dry endpoint; this command does not measure dryness.
        for group in groups():
            tip(p1000, len(group))
            mode(p1000, volume, slow=True)
            well = plate[group[0]["well"]]
            p1000.aspirate(volume, well.bottom(z=clearance))
            lift(p1000, well)
            p1000.dispense(volume, chute)
            p1000.drop_tip(chute)
            for sample in group:
                drying_started[(plate, sample["well"])] = time.monotonic()

    def wash_add(plate, source, total_volume):
        for group in groups():
            tip(p1000, len(group))
            destination = plate[group[0]["well"]]
            # 200 uL wash is split: no liquid + air can exceed a 200 uL tip.
            aliquots = (100.0, 100.0) if total_volume == 200 else (float(total_volume),)
            for aliquot in aliquots:
                mode(p1000, aliquot)
                source_height = aspiration_height(source, source_remaining[source] - aliquot * len(group))
                p1000.aspirate(aliquot, position(p1000, source, source_height))
                consume([source], aliquot * len(group))
                lift(p1000, source)
                p1000.air_gap(5, in_place=True)
                p1000.dispense(aliquot + 5, destination.top(z=-1))
                lift(p1000, destination)
            p1000.drop_tip(chute)

    def silica_wash(prepare_final=False):
        wash_add(p3, reservoir["A2"], 200)
        move(p3, WORKING_SLOT)
        for group in groups():
            tip(p1000, len(group))
            mix(p1000, p3[group[0]["well"]], 120, available_volume=205)
            p1000.drop_tip(chute)
        move(p3, mag)
        wait(30, "silica wash collection")
        if prepare_final:
            # Refill while 205 uL wash still covers the beads, before removal.
            reserve_tips(p50, [len(g) for g in groups()] * 2)
            reserve_tips(p1000, [len(g) for g in groups()] * 5)
        remove_bulk(p3, 200)

    def elute(plate, key, volume, mix_volume):
        # Rehydrate every pellet before mixing any well; complete columns use
        # all eight P50 channels to keep the last pellet from waiting to be wet.
        for group in groups():
            tip(p50, len(group))
            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, position(p50, source, source_height))
            consume(source_wells, volume)
            lift(p50, source)
            p50.dispense(volume, target.bottom(z=1), push_out=0)
            lift(p50, target)
            p50.drop_tip(chute)
            now = time.monotonic()
            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.")
        for group in groups():
            tip(p50, len(group))
            mix(p50, plate[group[0]["well"]], mix_volume, available_volume=volume)
            p50.drop_tip(chute)

    step(2)
    protocol.pause(
        f"SUPERVISED DEVELOPMENT RUN — {sample_count} fresh blood NK samples, 100,000 cells each. "
        "Use water/dye first to check inactive nozzles, pipette body, the C3 reservoir/chute clearance, "
        "gripper seating, source reserves and the low silica-eluate aspiration target. "
        "Load P1 with manually pelleted cells (500 x g, 5 min, 4 C) and 10 uL residual per active well. "
        "Load the specified cold/room/reservoir sources, clean P2 at A4, empty P3 at C2, and keep fresh P4 off deck. "
        "Check the reusable Thermocycler rubber seal and all labware identities. The kit is assumed sufficient for 16; "
        "the stated source reserves are provisional and must be physically checked. "
        "Do not put 20 uL tips on the Flex P50. Dry run still transfers every reagent/wash."
    )
    step(3)
    cold_add("pbs_source", p1)
    step(4)
    cold_spin("PBS WASH: centrifuge P1 at 500 x g for 5 minutes at 4 C; carefully remove supernatant, retaining 10 uL without disturbing the pellet.")
    step(5)
    cold_add("lysis_source", p1, mix_volume=60)
    step(6)
    cold_spin("NUCLEI: check lysis if needed, centrifuge P1 at 500 x g for 10 minutes at 4 C; carefully remove supernatant, retaining the confirmed 10 uL. Proceed promptly.")
    step(7)
    reserve_tips(p50, [1] * sample_count)
    reserve_tips(p1000, [len(g) for g in groups()] * 2)
    for sample in samples:
        dispense_source(p50, TAG_MIX_UL, cold[sample["tag_source"]], p1[sample["well"]],
                        mix_volume=20, destination_volume=TAG_REACTION_UL)
    step(8)
    no_tips()
    protocol.pause("Apply the qualified removable Heater-Shaker seal to P1. The rubber Thermocycler seal stays on the module and does not seal a plate on D1. Confirm all wells are sealed and clear hands before resuming.")
    step(9)
    move(p1, hs_adapter)
    if not dry_run:
        hs.set_and_wait_for_temperature(37)
        hs.set_and_wait_for_shake_speed(800)
    tag_start_time = time.monotonic()
    wait(1800, "tagmentation at 37 C / 800 rpm; 35 uL per sample")
    step(10)
    hs.deactivate_shaker()
    hs.deactivate_heater()
    hs.open_labware_latch()
    no_tips()
    protocol.pause("With shaking stopped and the D1 latch open, remove the seal from P1. Check for droplets trapped on the seal/walls and recover them manually if needed. Leave P1 seated, keep hands clear and resume; the gripper returns P1 to the open Thermocycler before liquid handling.")
    # Front D1 wells exceed SINGLE A1 reach. Use the vacant Thermocycler
    # position for all post-tagmentation additions, with native guards enabled.
    move(p1, tc)
    hs.close_labware_latch()
    step(11)
    # Add binding buffer to every sample before starting plate-to-plate transfer,
    # limiting extra tagmentation while earlier samples are being transferred.
    for group in groups():
        tip(p1000, len(group))
        mode(p1000, BINDING_BUFFER_UL, slow=True)
        source = reservoir["A1"]
        destination = p1[group[0]["well"]]
        source_height = aspiration_height(source, source_remaining[source] - BINDING_BUFFER_UL * len(group))
        p1000.aspirate(BINDING_BUFFER_UL, position(p1000, source, source_height))
        consume([source], BINDING_BUFFER_UL * len(group))
        lift(p1000, source)
        p1000.dispense(BINDING_BUFFER_UL, destination.bottom(z=1), push_out=0)
        lift(p1000, destination)
        p1000.drop_tip(chute)
        protocol.comment(f"TAG STOP {[s['well'] for s in group]}: binding buffer added "
                         f"{time.monotonic() - tag_start_time:.1f} s after the incubation timer began; simulation time is not a runtime estimate.")
    for group in groups():
        source = p1[group[0]["well"]]
        destination = p3[group[0]["well"]]
        tip(p1000, len(group))
        mix(p1000, source, 100, available_volume=BOUND_TRANSFER_UL)
        mode(p1000, BOUND_TRANSFER_UL, slow=True)
        # Near-total transfer: a small unmeasured residual may remain. Do not
        # interpret the nominal 160 uL command as measured quantitative recovery.
        p1000.aspirate(BOUND_TRANSFER_UL, source.bottom(z=MIN_LIQUID_CLEARANCE_MM))
        lift(p1000, source)
        p1000.dispense(BOUND_TRANSFER_UL, destination.bottom(z=1), push_out=0)
        lift(p1000, destination)
        p1000.drop_tip(chute)
    step(12)
    for sample in samples:
        dispense_source(p50, 3, room["A7"], p3[sample["well"]], mix_volume=30,
                        destination_volume=BOUND_TRANSFER_UL + 3, premix=True)
    step(13)
    no_tips()
    protocol.comment("Move P3 onto wet ice, then confirm the off-deck move; the five-minute timer follows.")
    protocol.move_labware(p3, OFF_DECK, use_gripper=False)
    wait(300, "silica binding ON ICE, performed off deck")
    protocol.move_labware(p3, WORKING_SLOT, use_gripper=False)
    tc.open_lid()
    protocol.comment("Remove used P1 from the Thermocycler, leaving its block empty for clean PCR plate P2.")
    protocol.move_labware(p1, OFF_DECK, use_gripper=False)
    step(14)
    move(p3, mag)
    wait(300, "initial silica bead collection")
    remove_bulk(p3, 158)  # 163 uL nominal binding mixture; leave 5 uL.
    step(15)
    silica_wash(prepare_final=True)
    step(16)
    silica_wash()
    step(17)
    remove_residual(p3, 5, DEEP_RESIDUAL_CLEARANCE_MM)
    no_tips()
    protocol.pause("Inspect P3 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(18)
    move(p3, WORKING_SLOT)
    elute(p3, "silica_elution_source", SILICA_ELUTION_UL, 25)
    wait(300, "silica DNA elution at room temperature")
    step(19)
    move(p3, mag)
    wait(300, "silica separation before PCR")
    move(p2, tc)
    for sample in samples:
        tip(p50)
        mode(p50, 33.5, slow=True)
        source = p3[sample["well"]]
        clearance = aspiration_height(source, SILICA_ELUTION_UL - 33.5, immersion=0.15)
        p50.flow_rate.aspirate = 5
        p50.aspirate(33.5, source.bottom(z=clearance))
        lift(p50, source)
        p50.dispense(33.5, p2[sample["well"]].bottom(z=1), push_out=0)
        lift(p50, p2[sample["well"]])
        p50.drop_tip(chute)
    step(20)
    move(p3, "A4")
    step(21)
    reserve_tips(p50, [1] * (3 * sample_count))
    for sample in samples:
        destination = p2[sample["well"]]
        dispense_source(p50, 2.5, cold[sample["i7_source"]], destination)
        dispense_source(p50, 2.5, cold[sample["i5_source"]], destination)
        dispense_source(p50, 11.5, cold[sample["pcr_mix_source"]], destination,
                        mix_volume=35, destination_volume=50)
    step(22)
    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=50)
        tc.set_block_temperature(98, hold_time_seconds=30, block_max_volume=50)
        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=50)
        tc.set_block_temperature(10, block_max_volume=50)
    tc.open_lid()
    tc.deactivate()
    step(23)
    move(p2, WORKING_SLOT)
    for sample in samples:
        dispense_source(p1000, 60, room[sample["spri_source"]], p2[sample["well"]],
                        mix_volume=80, destination_volume=110, premix=True)
    wait(300, "SPRI binding at room temperature")
    step(24)
    move(p2, mag)
    wait(300, "SPRI bead collection")
    # A complete fresh rack covers this uninterrupted block even at N=16.
    # Reserve before removing the 110 uL binding mixture, while beads are wet.
    reserve_tips(p50, [len(g) for g in groups()] * 2)
    reserve_tips(p1000, [len(g) for g in groups()] * 6)
    remove_bulk(p2, 105)  # 110 uL mixture, leaving 5 uL before the 180 uL wash.
    step(25)
    wash_add(p2, reservoir["A3"], 180)
    wait(30, "first SPRI ethanol wash; no mixing on magnet")
    remove_bulk(p2, 180)
    step(26)
    wash_add(p2, reservoir["A3"], 180)
    wait(30, "second SPRI ethanol wash; no mixing on magnet")
    remove_bulk(p2, 180)
    step(27)
    remove_residual(p2, 5, PCR_RESIDUAL_CLEARANCE_MM)
    no_tips()
    protocol.comment("Prepare P4 beside the robot before confirming these plate exchanges so drying is not prolonged.")
    protocol.move_labware(p3, OFF_DECK, use_gripper=False)
    protocol.move_labware(p4, "A4", use_gripper=False)
    protocol.pause("Inspect P2 SPRI beads on B2: allow residual ethanol to evaporate until matte, normally 2–5 minutes, without cracking. Include time already spent on residual removal and the A4 exchange. Confirm fresh P4 is at A4 and resume promptly for 20 uL elution.")
    step(28)
    move(p2, WORKING_SLOT)
    elute(p2, "spri_elution_source", 20, 15)
    wait(300, "final library elution at room temperature")
    step(29)
    move(p2, mag)
    wait(300, "final SPRI separation")
    step(30)
    move(p4, WORKING_SLOT)
    step(31)
    for sample in samples:
        tip(p50)
        mode(p50, FINAL_RECOVERY_UL, slow=True)
        source = p2[sample["well"]]
        p50.flow_rate.aspirate = 5
        p50.aspirate(FINAL_RECOVERY_UL, source.bottom(z=PCR_RESIDUAL_CLEARANCE_MM))
        lift(p50, source)
        p50.dispense(FINAL_RECOVERY_UL, p4[sample["well"]].bottom(z=1), push_out=0)
        lift(p50, p4[sample["well"]])
        p50.drop_tip(chute)
    step(32)
    no_tips()
    protocol.comment(f"FINISHED: {sample_count} libraries in P4 at {WORKING_SLOT}; programmed recovery {FINAL_RECOVERY_UL:g} uL from 20 uL elution. "
                     "Keep the sample/index map. Quantify and inspect fragment profiles; successful simulation is not wet ATAC validation.")
    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.")
