import csv
from collections import defaultdict

# ----------------------------
# Ficheros de entrada/salida
# ----------------------------
ROUGH_FILE = "rough_mapping.csv"
WN_MCR_FILE = "wn_MCR_s.csv"
OUT_FILE = "sp_mapping.csv"

# ----------------------------
# 1. Cargar wn_MCR_s.csv en memoria
#    synset_id30 -> lista de lemas en español
# ----------------------------
synset_to_lemmas = defaultdict(list)

with open(WN_MCR_FILE, newline="", encoding="utf-8") as f:
    reader = csv.DictReader(f)
    for row in reader:
        synset = row["Synset"].strip()
        word = row["Word"].strip().strip("'")
        if synset and word:
            synset_to_lemmas[synset].append(word)

# Eliminar duplicados conservando orden
for synset in synset_to_lemmas:
    synset_to_lemmas[synset] = list(dict.fromkeys(synset_to_lemmas[synset]))


# ----------------------------
# 2. Procesar rough_mapping.csv
# ----------------------------
cont_sin_correspondencia = 0

with open(ROUGH_FILE, newline="", encoding="utf-8") as fin, \
     open(OUT_FILE, "w", newline="", encoding="utf-8") as fout:

    reader = csv.reader(fin)
    writer = csv.writer(fout)

    # Cabecera
    header = next(reader)
    writer.writerow(header)

    for row in reader:
        if len(row) < 3:
            # línea defectuosa -> copiar tal cual
            writer.writerow(row)
            continue

        pos = row[0]
        synset16 = row[1]
        bag = row[2].strip()

        if bag == "":
            # No hay bag: copiar tal cual
            writer.writerow(row)
            continue

        # Partir los elementos del bag por ";"
        elementos = [e.strip() for e in bag.split(";")]

        nuevos_elementos = []

        for elem in elementos:
            # Formato esperado: synset30:lemas_en
            if ":" not in elem:
                nuevos_elementos.append(elem)
                continue

            synset30, _ = elem.split(":", 1)
            synset30 = synset30.strip()

            if synset30 in synset_to_lemmas:
                lemas_sp = synset_to_lemmas[synset30]
                lista_sp = "|".join(lemas_sp)
            else:
                lista_sp = "no_correspondence"
                cont_sin_correspondencia += 1

            nuevos_elementos.append(f"{synset30}:{lista_sp}")

        nuevo_bag = " ; ".join(nuevos_elementos)

        writer.writerow([pos, synset16, nuevo_bag])

# ----------------------------
# 3. Mostrar contador
# ----------------------------
print(f"Sin correspondencia: {cont_sin_correspondencia}")
