from pathlib import Path

import pandas as pd
import networkx as nx
import plotly.graph_objects as go


class TimelineGraphEngine:

    def __init__(self, excel_path):
        self.excel_path = Path(excel_path)

        if not self.excel_path.exists():
            raise FileNotFoundError(
                f"No existe el archivo: {self.excel_path}"
            )

    def load(self, sheet_name=0):

        self.df = pd.read_excel(
            self.excel_path,
            sheet_name=sheet_name
        )

        self.df = self.df.dropna(
            how="all"
        ).reset_index(drop=True)

        return self.df

    def autodetect_columns(self):

        cols = {
            str(c).lower().strip(): c
            for c in self.df.columns
        }

        date_col = None

        for k, v in cols.items():

            if k in [
                "fecha",
                "date",
                "year",
                "año",
                "ano",
                "tiempo"
            ]:
                date_col = v
                break

        label_col = self.df.columns[0]

        for k, v in cols.items():

            if k in [
                "evento",
                "nombre",
                "name",
                "title",
                "titulo"
            ]:
                label_col = v
                break

        return date_col, label_col

    def build_graph(self):

        date_col, label_col = self.autodetect_columns()

        G = nx.DiGraph()

        for idx, row in self.df.iterrows():

            label = str(row[label_col])

            if date_col:
                date_value = row[date_col]
            else:
                date_value = idx

            G.add_node(
                label,
                index=idx,
                date=str(date_value)
            )

        self.graph = G

        return G

    def render_middle_timeline(
        self,
        output_html="outputs/timeline_middle.html"
    ):

        if not hasattr(self, "df"):
            self.load()

        if not hasattr(self, "graph"):
            self.build_graph()

        x = []
        y = []
        text = []

        for node, data in self.graph.nodes(data=True):

            x.append(data["index"])
            y.append(0)
            text.append(
                f"{node}<br>{data['date']}"
            )

        fig = go.Figure()

        fig.add_trace(
            go.Scatter(
                x=x,
                y=y,
                mode="markers+text",
                text=text,
                textposition="top center"
            )
        )

        fig.update_layout(
            title="Timeline Central",
            showlegend=False,
            height=700
        )

        output_html = Path(output_html)

        output_html.parent.mkdir(
            parents=True,
            exist_ok=True
        )

        fig.write_html(output_html)

        return output_html
