import streamlit as st
from utils.translations import _

def ajouter_produit(G):
    st.markdown(f"## {str(_('pages.personnalisation.add_new_product'))}")
    new_prod = st.text_input(str(_("pages.personnalisation.new_product_name")), key="new_prod")
    if new_prod:
        ops_dispo = sorted([
            n for n, d in G.nodes(data=True)
            if d.get("niveau") == "10"
            and any(G.has_edge(p, n) and G.nodes[p].get("niveau") == "0" for p in G.predecessors(n))
        ])
        sel_new_op = st.selectbox(str(_("pages.personnalisation.assembly_operation")), [str(_("pages.personnalisation.none"))] + ops_dispo, index=0)
        niveau1 = sorted([n for n, d in G.nodes(data=True) if d.get("niveau") == "1"])
        sel_comps = st.multiselect(str(_("pages.personnalisation.components_to_link")), options=niveau1)
        if st.button(str(_("pages.personnalisation.create_product"))):
            G.add_node(new_prod, niveau="0", personnalisation="oui", label=new_prod)
            if sel_new_op != str(_("pages.personnalisation.none")):
                G.add_edge(new_prod, sel_new_op)
            for comp in sel_comps:
                G.add_edge(new_prod, comp)
            st.success(f"{new_prod} {str(_('pages.personnalisation.added'))}")
    return G
