"""
Claves Redis por job de import CSV (layouts_csv): las de storage_keys más extras por módulo.
Usado por la limpieza periódica (victor "el senior de limpieza") para saber si un job sigue vivo en Redis.
"""
from __future__ import annotations

from typing import Any, List

from . import storage as common_storage

# Prefijo en nombre de archivo `{prefix}_{uuid}.csv` -> job_type (vacío = solo `{uuid}.csv`)
FILE_PREFIX_TO_JOB_TYPE: dict[str, str] = {
    "veh": "veh",
    "fa": "fa",
    "trl": "trl",
    "trp": "trp",
    "ped": "ped",
    "part": "part",
    "er": "er",
    "cb": "cb",
    "drv": "drv",
    "cls": "cls",
    "cp": "cp",
    "bom": "bom",
    "exp": "exp",
    "crreg": "crreg",
}


def all_redis_keys_for_layout_import(job_type: str, job_id: str) -> List[str]:
    """Todas las claves Redis que pueden existir para un job (file, meta, error_lines, extras)."""
    file_k, meta_k, err_k = common_storage.storage_keys(job_type, job_id)
    keys: List[str] = [file_k, meta_k, err_k]
    if job_type == "veh":
        keys.append(f"veh_import_status:{job_id}")
    elif job_type == "trl":
        keys.append(f"trl_import_status:{job_id}")
    elif job_type == "trp":
        keys.append(f"trp_import_status:{job_id}")
    elif job_type == "drv":
        keys.append(f"drv_import_status:{job_id}")
        keys.append(f"drv_import_transporter_map:{job_id}")
    return keys


def any_layout_import_key_exists(redis_client: Any, job_type: str, job_id: str) -> bool:
    for k in all_redis_keys_for_layout_import(job_type, job_id):
        if redis_client.exists(k):
            return True
    return False


def delete_extra_layout_import_keys_from_redis(redis_client: Any, job_type: str, job_id: str) -> None:
    """Borra claves que delete_import_from_redis no cubre (status, mapas)."""
    extras: list[str] = []
    if job_type == "veh":
        extras.append(f"veh_import_status:{job_id}")
    elif job_type == "trl":
        extras.append(f"trl_import_status:{job_id}")
    elif job_type == "trp":
        extras.append(f"trp_import_status:{job_id}")
    elif job_type == "drv":
        extras.append(f"drv_import_status:{job_id}")
        extras.append(f"drv_import_transporter_map:{job_id}")
    if extras:
        try:
            redis_client.delete(*extras)
        except Exception:
            pass
