"""Shared utility helpers for sequencer workers."""

from __future__ import annotations

from typing import Any, Dict


def clean_string(value: Any) -> str:
    if value is None:
        return ""
    if isinstance(value, str):
        return value.strip()
    return str(value).strip()


def normalize_status(value: Any) -> str:
    return clean_string(value).lower()


def get_row_number(row: Dict[str, Any], fallback_index: int) -> int:
    for key, is_zero_based in (
        ("row_number", False),
        ("row_index", True),
        ("__fm_row_index__", True),
    ):
        if key in row:
            try:
                num = int(row.get(key))
                return num + (1 if is_zero_based else 0)
            except (TypeError, ValueError):
                continue
    return fallback_index + 1


def should_skip_row(row: Dict[str, Any], campaign_id: str, writeback: Dict[str, Any]) -> bool:
    if not writeback or not writeback.get("enabled", True):
        return False
    status_columns = [
        writeback.get("status_column"),
        "submission_status",
        "Sequencer Status",
    ]
    campaign_columns = [
        writeback.get("campaign_column"),
        "campaign_id",
        "Sequencer Campaign",
    ]

    status_val = ""
    for column in status_columns:
        if column and column in row:
            status_val = normalize_status(row.get(column))
            if status_val:
                break

    campaign_val = ""
    for column in campaign_columns:
        if column and column in row:
            campaign_val = clean_string(row.get(column))
            if campaign_val:
                break

    return status_val in {"enrolled", "exists"} and campaign_val == campaign_id
