"""
HTGAA 2026 — Week 3: Lab Automation
Protocol: "ELM Habitat Cross-Section"
Author:   Arman Saadatkhah (Zarias Sacrati Aelius)

Artistic concept:
    A 96-well plate is used as a canvas to depict a cross-sectional view of the
    Multi-Trophic Myco-Foundry habitat proposed in Week 1 HW. Three coloured
    dyes represent the three biological layers of the deep-space living material:

        Structural Shell  — Coomassie Blue    (outermost ring)
        Vascular System   — Sunset Yellow     (middle ring)
        Metabolic Hub     — Brilliant Green   (innermost core)

    Wells are classified by their Euclidean distance from the plate centre
    (between wells D6/D7/E6/E7) on a 8x12 grid, producing concentric rings
    that mimic the habitat's layered architecture.

AI disclosure:
    Claude Sonnet 4.6 (Anthropic) assisted with script structure, distance
    calculations, and transfer logic. Artistic concept and biological framing
    were developed by the student.
"""

from opentrons import protocol_api
import math

metadata = {
    'protocolName': 'ELM Habitat Cross-Section — Opentrons Art',
    'author': 'Arman Saadatkhah <saadatarman@gmail.com>',
    'description': (
        'Concentric ring artwork on a 96-well plate representing the three '
        'biological layers of the Multi-Trophic Myco-Foundry ELM habitat: '
        'Structural Shell (blue), Vascular System (orange), Metabolic Hub (green).'
    ),
    'apiLevel': '2.14',
}

# ── Well classification parameters ───────────────────────────────────────────
ROWS = list('ABCDEFGH')
COLS = list(range(1, 13))
ROW_CENTER = 3.5    # geometric centre between rows D (idx 3) and E (idx 4)
COL_CENTER = 5.5    # geometric centre between cols 6 (idx 5) and 7 (idx 6)

SHELL_MIN,    SHELL_MAX    = 3.0, 5.0   # outer ring
VASCULAR_MIN, VASCULAR_MAX = 1.5, 3.0  # middle ring
# inner core: r < 1.5

VOLUME_UL = 60   # µL per well


def classify_well(row_idx: int, col_idx: int) -> str:
    """Return 'shell', 'vascular', 'hub', or 'empty' for a well."""
    d = math.sqrt((row_idx - ROW_CENTER) ** 2 + (col_idx - COL_CENTER) ** 2)
    if d < 1.5:
        return 'hub'
    elif VASCULAR_MIN <= d < VASCULAR_MAX:
        return 'vascular'
    elif SHELL_MIN <= d <= SHELL_MAX:
        return 'shell'
    return 'empty'


def run(protocol: protocol_api.ProtocolContext) -> None:

    # ── Labware ──────────────────────────────────────────────────────────────
    tiprack_1 = protocol.load_labware('opentrons_96_tiprack_300ul', 1)
    tiprack_2 = protocol.load_labware('opentrons_96_tiprack_300ul', 4)
    plate     = protocol.load_labware('corning_96_wellplate_360ul_flat', 2)
    reservoir = protocol.load_labware('usascientific_12_reservoir_22ml', 3)

    # ── Pipette ──────────────────────────────────────────────────────────────
    p300 = protocol.load_instrument(
        'p300_single_gen2', 'left', tip_racks=[tiprack_1, tiprack_2]
    )

    # ── Dye sources (fill reservoir wells before run) ────────────────────────
    # Reservoir A1: Coomassie Blue    — min 3.0 mL for 40 wells × 60 µL
    # Reservoir A2: Sunset Yellow     — min 2.0 mL for 28 wells × 60 µL
    # Reservoir A3: Brilliant Green   — min 0.5 mL for  4 wells × 60 µL
    blue   = reservoir['A1']   # Structural Shell
    orange = reservoir['A2']   # Vascular System
    green  = reservoir['A3']   # Metabolic Hub

    # ── Classify all 96 wells into layers ────────────────────────────────────
    shell_wells    = []
    vascular_wells = []
    hub_wells      = []

    for ri, row in enumerate(ROWS):
        for ci in range(len(COLS)):
            col = COLS[ci]
            kind = classify_well(ri, ci)
            well_name = f"{row}{col}"
            if kind == 'shell':
                shell_wells.append(plate[well_name])
            elif kind == 'vascular':
                vascular_wells.append(plate[well_name])
            elif kind == 'hub':
                hub_wells.append(plate[well_name])

    protocol.comment(
        f"Well counts — Shell: {len(shell_wells)} | "
        f"Vascular: {len(vascular_wells)} | Hub: {len(hub_wells)}"
    )

    # ── Layer 1: Structural Shell (outermost, blue) ──────────────────────────
    protocol.comment("Dispensing Structural Shell (blue)...")
    p300.transfer(
        VOLUME_UL,
        blue,
        shell_wells,
        new_tip='always',
        blow_out=True,
        blowout_location='source well',
    )

    # ── Layer 2: Vascular System (middle, orange) ────────────────────────────
    protocol.comment("Dispensing Vascular System (orange)...")
    p300.transfer(
        VOLUME_UL,
        orange,
        vascular_wells,
        new_tip='always',
        blow_out=True,
        blowout_location='source well',
    )

    # ── Layer 3: Metabolic Hub (innermost, green) ─────────────────────────────
    protocol.comment("Dispensing Metabolic Hub (green)...")
    p300.transfer(
        VOLUME_UL,
        green,
        hub_wells,
        new_tip='always',
        blow_out=True,
        blowout_location='source well',
    )

    protocol.comment("Protocol complete. ELM Habitat Cross-Section artwork finished.")
