#!/usr/bin/env python3
"""Dependency-free configuration helpers for dense LIVECell experiments."""

from __future__ import annotations

import argparse
from typing import Any, Dict, List


DENSE_MAX_DETECTIONS = 3000
DENSE_TRAIN_CROP_SIZE = 512
LIVECELL_AREA_RANGES: List[List[float]] = [
    [0.0, 1.0e10],
    [0.0, 500.0],
    [500.0, 1500.0],
    [1500.0, 1.0e10],
]
LIVECELL_AREA_RANGE_LABELS = ["all", "small", "medium", "large"]


def apply_livecell_dense_protocol(args: argparse.Namespace) -> argparse.Namespace:
    """Resolve dense settings while preserving legacy behavior without the flag."""
    if not args.livecell_dense_protocol:
        return args

    args.max_instances_per_image = 0
    if args.train_crop_size < 0:
        args.train_crop_size = DENSE_TRAIN_CROP_SIZE
    args.eval_max_predictions = DENSE_MAX_DETECTIONS
    args.box_detections_per_image = DENSE_MAX_DETECTIONS
    args.rpn_pre_nms_top_n_train = max(args.rpn_pre_nms_top_n_train, 6000)
    args.rpn_post_nms_top_n_train = max(args.rpn_post_nms_top_n_train, 3000)
    args.rpn_pre_nms_top_n_test = max(args.rpn_pre_nms_top_n_test, 6000)
    args.rpn_post_nms_top_n_test = max(args.rpn_post_nms_top_n_test, DENSE_MAX_DETECTIONS)
    args.box_batch_size_per_image = max(args.box_batch_size_per_image, 512)
    return args


def dense_protocol_manifest(args: argparse.Namespace) -> Dict[str, Any]:
    """Return the resolved protocol fields that must be recorded with a run."""
    return {
        "name": "livecell_dense_eval_compatible_v1" if args.livecell_dense_protocol else "legacy_v1",
        "all_training_instances": args.max_instances_per_image == 0,
        "training_crop_size": max(0, int(args.train_crop_size)),
        "all_validation_instances": bool(args.livecell_dense_protocol),
        "max_detections_per_image": int(args.eval_max_predictions),
        "livecell_area_thresholds_pixels": [500, 1500] if args.livecell_dense_protocol else None,
        "reports_afnr": True,
        "official_model_replication": False,
    }
