# app/src/market_data/acquisition/symbols.py

from __future__ import annotations

from collections.abc import Sequence


# Привести идентификатор торгового инструмента к базовой канонической форме.
def normalize_symbol(raw_symbol: str) -> str:
    return (raw_symbol or "").strip().upper()


# Сформировать упорядоченные варианты идентификатора инструмента.
def symbol_candidates(raw_symbol: str) -> list[str]:
    value = normalize_symbol(raw_symbol)

    if not value:
        return []

    candidates = [value]

    compact = value.replace("%2F", "/")

    if compact not in candidates:
        candidates.append(compact)

    no_spaces = compact.replace(" ", "")

    if no_spaces not in candidates:
        candidates.append(no_spaces)

    return candidates


# Найти индекс первого доступного символа с учётом порядка кандидатов.
def resolve_symbol_index(
    raw_symbol: str,
    available_symbols: Sequence[str],
) -> int | None:
    for candidate in symbol_candidates(raw_symbol):
        for index, available_symbol in enumerate(available_symbols):
            if normalize_symbol(available_symbol) == candidate:
                return index

    return None