"""Choose one stage-1 follow-up from per-layer probe rows. No training."""

FINAL_LAYER = 11
SCORE_MARGIN = 0.30
TIME_RATIO = 1.15


def choose_layer_experiment(rows, final_layer=FINAL_LAYER):
    """Return the single branch justified by the probe.

    ``rows`` is one dict per block, with ``score`` and train ``crackle_time``.
    A middle layer is used alone only when its probe Score beats the last block
    by SCORE_MARGIN. Concatenation is used only when the last block is the best
    probe and crackle time-concentration peaks earlier by TIME_RATIO.
    """
    if len(rows) != final_layer + 1:
        raise ValueError('expected {} layer rows, got {}'.format(final_layer + 1, len(rows)))
    final_score = float(rows[final_layer]['score'])
    best = max(range(len(rows)), key=lambda i: (float(rows[i]['score']), i == final_layer))
    best_score = float(rows[best]['score'])
    if best != final_layer and best_score > final_score + SCORE_MARGIN:
        return {
            'decision': 'layer',
            'feature_layer': best,
            'feature_layer_aux': -1,
            'reason': 'layer {} probe Score {:.2f} beats layer {} ({:.2f}) by {:.2f}'.format(
                best, best_score, final_layer, final_score, best_score - final_score),
        }
    if best == final_layer:
        peak = max(range(final_layer), key=lambda i: float(rows[i]['crackle_time']))
        peak_value = float(rows[peak]['crackle_time'])
        final_value = float(rows[final_layer]['crackle_time'])
        if final_value > 0.0 and peak_value >= TIME_RATIO * final_value:
            return {
                'decision': 'concat',
                'feature_layer': final_layer,
                'feature_layer_aux': peak,
                'reason': (
                    'crackle time concentration peaks at layer {} ({:.3f}) '
                    'versus layer {} ({:.3f})'.format(peak, peak_value, final_layer, final_value)
                ),
            }
    return {
        'decision': 'stop',
        'feature_layer': final_layer,
        'feature_layer_aux': -1,
        'reason': (
            'no layer beats the final probe by {:.2f}, and crackle time '
            'concentration does not peak earlier by {:.0f}%'.format(
                SCORE_MARGIN, (TIME_RATIO - 1.0) * 100.0)
        ),
    }
