"""Shared utilities for activation workers (HeyReach, JustCall, etc.)."""

from __future__ import annotations

import re
from typing import Any, Dict


def clean_string(value: Any) -> str:
    """Strip and normalize a value to string."""
    if value is None:
        return ""
    if isinstance(value, str):
        return value.strip()
    return str(value).strip()


def normalize_status(value: Any) -> str:
    """Normalize status value to lowercase string."""
    return clean_string(value).lower()


def normalize_header_key(value: Any) -> str:
    """Normalize header to alphanumeric lowercase for matching."""
    text = clean_string(value).lower()
    return re.sub(r"[^a-z0-9]", "", text)


def get_row_number(row: Dict[str, Any], fallback_index: int, starting_row: int) -> int:
    """
    Extract row number from row dict, checking common keys.

    Checks row_number (1-based), row_index (0-based), __fm_row_index__ (0-based).
    Falls back to starting_row + fallback_index if not found.
    """
    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 starting_row + fallback_index


def should_skip_row(
    row: Dict[str, Any],
    campaign_id: str,
    writeback: Dict[str, Any],
) -> bool:
    """
    Check if row should be skipped because it's already enrolled in this campaign.

    Looks at writeback status_column and campaign_column to detect prior enrollment.
    """
    if not writeback or not writeback.get("enabled", True):
        return False
    status_col = writeback.get("status_column")
    campaign_col = writeback.get("campaign_column")
    if not status_col or not campaign_col:
        return False
    status_val = normalize_status(row.get(status_col))
    campaign_val = clean_string(row.get(campaign_col))
    return status_val == "enrolled" and campaign_val == campaign_id


__all__ = [
    "clean_string",
    "normalize_status",
    "normalize_header_key",
    "get_row_number",
    "should_skip_row",
]
