from __future__ import annotations

import logging
from typing import Any

from config.app_config import LOTE_PATH, NO_INICIADOS_DIR
from utils.json_helper import write_json

logger = logging.getLogger(__name__)


def ingest(raw_data: dict[str, Any] | list[str]) -> dict[str, Any]:
    """Save a raw opportunity list to storage/no_iniciados/lote.json."""
    items = _normalize(raw_data)

    if not items:
        raise ValueError("No se recibieron oportunidades válidas para ingestar.")

    payload = {"pendientes": items}
    NO_INICIADOS_DIR.mkdir(parents=True, exist_ok=True)
    write_json(LOTE_PATH, payload)

    logger.info("Ingesta completada: %s oportunidades guardadas en %s", len(items), LOTE_PATH)
    return payload


def _normalize(raw_data: dict[str, Any] | list[str]) -> list[str]:
    if isinstance(raw_data, list):
        source = raw_data
    elif isinstance(raw_data, dict):
        source = (
            raw_data.get("opportunities")
            or raw_data.get("oportunidades")
            or raw_data.get("pendientes")
            or []
        )
    else:
        raise TypeError("raw_data debe ser un dict o una lista de códigos de oportunidad.")

    seen: set[str] = set()
    items: list[str] = []
    for item in source:
        code = str(item).strip()
        if not code or code in seen:
            continue
        seen.add(code)
        items.append(code)
    return items
