import pandas as pd
import plotly.graph_objects as go

# Read the CSV file into a Pandas DataFrame
file_path = "texts_by_period_and_location_saparated_by_periods_in_columns.csv"
df = pd.read_csv(file_path)

# Define the columns to summarize
columns_to_summarize = ["ancient", "old", "middle", "new", "late"]

# Group the data by the "place" column and calculate sums within each group
grouped = df.groupby("place")[columns_to_summarize].sum().reset_index()

# Create a stacked bar chart using Plotly
fig = go.Figure()

# Add a bar trace for each category
for col in columns_to_summarize:
    fig.add_trace(go.Bar(x=grouped["place"], y=grouped[col], name=col, text=grouped[col], textposition='auto'))

# Customize the layout
fig.update_layout(
    title="Summary of Categories by Place with Selection",
    xaxis_title="Place",
    yaxis_title="Total Count",
    xaxis=dict(categoryorder='total descending'),
    barmode='stack'
)

# Enable selection by clicking
fig.update_traces(selector=dict(mode='lasso'))

# Enable searching for place names
fig.update_layout(updatemenus=[
    {
        'buttons': [
            {
                'args': [{'visible': [True] * len(grouped)}],
                'label': 'Show All',
                'method': 'restyle'
            },
            {
                'args': [{'visible': [grouped["place"] == place for place in grouped["place"]]}],
                'label': 'Select Place',
                'method': 'restyle'
            }
        ],
        'direction': 'down',
        'showactive': False,
        'x': 0.1,
        'xanchor': 'left',
        'y': 1.1,
        'yanchor': 'top'
    }
])

# Show the interactive graph
fig.show()
