import json

import networkx as nx
import streamlit as st

from utils.translations import get_translation as _


def importer_exporter_graph(G: nx.DiGraph) -> nx.DiGraph:
    """Affiche l'interface d'import/export des configurations personnalisees du graphe."""
    st.markdown(f"## {_('pages.personnalisation.save_restore_config')}")
    if st.button(str(_("pages.personnalisation.export_config")), icon=":material/save:"):
        nodes = [n for n, d in G.nodes(data=True) if d.get("personnalisation") == "oui"]
        edges = [(u, v) for u, v in G.edges() if u in nodes]
        conf = {"nodes": nodes, "edges": edges}
        json_str = json.dumps(conf, ensure_ascii=False)
        st.download_button(
            label=str(_("pages.personnalisation.download_json")),
            data=json_str,
            file_name="config_personnalisation.json",
            mime="application/json",
            icon=":material/save:"
        )

    uploaded = st.file_uploader(str(_("pages.personnalisation.import_config")), type=["json"])
    if uploaded:
        if uploaded.size > 100 * 1024:
            st.error(_("pages.personnalisation.file_too_large"))
        else:
            try:
                conf = json.loads(uploaded.read().decode("utf-8"))
                all_nodes = conf.get("nodes", [])
                all_edges = conf.get("edges", [])

                if not all_nodes:
                    st.warning(_("pages.personnalisation.no_products_found"))
                else:
                    st.markdown(f"### {_('pages.personnalisation.select_products_to_restore')}")
                    sel_nodes = st.multiselect(
                        str(_("pages.personnalisation.products_to_restore")),
                        options=all_nodes,
                        default=all_nodes,
                        key="restaurer_selection"
                    )

                    if st.button(str(_("pages.personnalisation.restore_selected")), type="primary", icon=":material/history:"):
                        for node in sel_nodes:
                            if not G.has_node(node):
                                G.add_node(node, niveau="0", personnalisation="oui", label=node)

                        for u, v in all_edges:
                            if u in sel_nodes and v in sel_nodes + list(G.nodes()) and not G.has_edge(u, v):
                                G.add_edge(u, v)

                        st.success(_("pages.personnalisation.config_restored"))
            except Exception as e:
                st.error(f"{_('errors.import_error')} {e}")

    return G
