File size: 42,671 Bytes
6277fe0
abb0fcc
b560569
575b933
b0464a9
87a87e7
791c130
 
266ae82
8673558
63031db
 
f7fc39b
575b933
266ae82
575b933
 
 
811c2ba
 
575b933
 
 
 
 
266ae82
6277fe0
 
 
9d99925
8cf83ef
6277fe0
2601f1c
 
abb0fcc
2601f1c
 
b0464a9
2a3b22e
3b4dccb
2a3b22e
b0464a9
2a3b22e
adb3bbe
6277fe0
67742c4
a342a6b
6a8e128
 
 
 
 
2601f1c
67742c4
6277fe0
 
 
 
adb3bbe
a342a6b
d33040c
 
 
6277fe0
a342a6b
575b933
0612e1d
4ad44b9
266ae82
0612e1d
adb3bbe
791c130
 
d33040c
 
 
 
6277fe0
2a3b22e
4ad44b9
2a3b22e
a342a6b
 
2a3b22e
8673558
d33040c
 
2601f1c
d33040c
6277fe0
8673558
791c130
d33040c
 
791c130
6277fe0
 
 
8673558
d33040c
791c130
 
d33040c
3b902c0
 
791c130
 
 
 
 
6277fe0
266ae82
d33040c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
266ae82
d33040c
6a8e128
6277fe0
 
 
 
ddd95f0
8673558
 
6a8e128
6277fe0
 
 
2601f1c
6277fe0
2601f1c
 
 
 
6277fe0
2601f1c
 
 
 
 
 
6277fe0
2601f1c
 
 
 
6277fe0
 
 
 
 
092a033
6277fe0
 
2601f1c
6277fe0
 
2601f1c
 
 
6277fe0
 
 
 
 
 
 
 
 
 
 
 
2601f1c
 
8673558
 
6277fe0
 
 
2601f1c
 
 
 
6277fe0
 
 
2601f1c
6277fe0
 
 
 
 
 
 
 
2601f1c
ddd95f0
 
eb46c40
2601f1c
6277fe0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8673558
6277fe0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ddd95f0
2601f1c
 
 
 
 
092a033
 
6277fe0
abb0fcc
6277fe0
abb0fcc
 
 
6277fe0
 
092a033
abb0fcc
2601f1c
 
6277fe0
abb0fcc
6277fe0
092a033
6277fe0
2601f1c
6277fe0
 
 
2601f1c
ddd95f0
2601f1c
eb46c40
2601f1c
eb46c40
 
6277fe0
 
eb46c40
6277fe0
2601f1c
6277fe0
 
ddd95f0
2601f1c
 
 
 
 
6277fe0
 
 
 
 
 
 
 
ddd95f0
998bc4b
ddd95f0
2601f1c
6277fe0
 
 
 
2601f1c
 
 
6277fe0
365263e
2601f1c
 
 
092a033
2601f1c
 
6277fe0
092a033
 
6277fe0
092a033
2601f1c
 
 
365263e
2601f1c
 
 
6277fe0
 
 
2601f1c
 
 
6277fe0
365263e
092a033
6277fe0
092a033
 
2601f1c
6277fe0
 
 
 
 
 
eb46c40
d33040c
6277fe0
 
 
 
 
 
 
8673558
6277fe0
 
 
 
2601f1c
6277fe0
 
 
 
 
 
eb46c40
6277fe0
 
 
 
 
 
 
 
 
 
eb46c40
6277fe0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ddd95f0
6277fe0
 
2601f1c
6277fe0
 
 
 
 
 
2601f1c
6277fe0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ddd95f0
6277fe0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2601f1c
6277fe0
2601f1c
092a033
6277fe0
 
 
 
 
 
2601f1c
8673558
6277fe0
dc88746
6277fe0
dc88746
6277fe0
 
dc88746
092a033
998bc4b
ddd95f0
 
eb46c40
ddd95f0
 
6277fe0
 
2601f1c
ddd95f0
 
 
6277fe0
8673558
2601f1c
ddd95f0
 
 
6277fe0
 
 
ddd95f0
 
8673558
d33040c
6277fe0
2601f1c
6277fe0
092a033
2601f1c
 
6277fe0
2601f1c
 
 
 
6277fe0
2601f1c
 
6277fe0
 
2601f1c
 
 
6277fe0
 
2601f1c
 
 
6277fe0
 
2601f1c
8673558
2601f1c
 
266ae82
092a033
266ae82
8673558
6277fe0
 
 
 
 
8673558
6277fe0
 
 
d33040c
ddd95f0
2601f1c
092a033
6277fe0
 
092a033
6277fe0
092a033
 
 
6277fe0
 
2601f1c
6277fe0
 
ddd95f0
6277fe0
 
 
 
 
 
2601f1c
6277fe0
dc88746
266ae82
 
6277fe0
 
 
 
8673558
6277fe0
 
 
 
 
 
ddd95f0
6277fe0
 
 
 
 
 
2601f1c
6277fe0
6a8e128
791c130
266ae82
2601f1c
eb46c40
a342a6b
adb3bbe
06d22e5
d33040c
 
 
 
4ad44b9
 
eb46c40
a342a6b
 
575b933
d33040c
 
 
6277fe0
d33040c
a342a6b
d33040c
 
2601f1c
a342a6b
 
266ae82
a342a6b
538b42b
2601f1c
266ae82
 
ddd95f0
266ae82
6277fe0
 
8673558
6277fe0
266ae82
 
6277fe0
ddd95f0
266ae82
 
6277fe0
2601f1c
6277fe0
2601f1c
266ae82
 
adb3bbe
575b933
d33040c
575b933
 
 
d33040c
2601f1c
a342a6b
d33040c
6277fe0
092a033
2601f1c
6277fe0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
# app.py
# (Showing relevant parts that need modification)
import gradio as gr
import pandas as pd
import os
import logging
import matplotlib
matplotlib.use('Agg') # Set backend for Matplotlib to avoid GUI conflicts with Gradio
import matplotlib.pyplot as plt
import time # For profiling if needed
from datetime import datetime, timedelta # Added timedelta
import numpy as np

# --- Module Imports ---
from gradio_utils import get_url_user_token
# Functions from newly created/refactored modules
from config import (
    LINKEDIN_CLIENT_ID_ENV_VAR, BUBBLE_APP_NAME_ENV_VAR,
    BUBBLE_API_KEY_PRIVATE_ENV_VAR, BUBBLE_API_ENDPOINT_ENV_VAR,
    PLOT_ID_TO_FORMULA_KEY_MAP)
from state_manager import process_and_store_bubble_token
from sync_logic import sync_all_linkedin_data_orchestrator
from ui_generators import (
    display_main_dashboard,
    run_mentions_tab_display,
    run_follower_stats_tab_display,
    build_analytics_tab_plot_area,
    BOMB_ICON, EXPLORE_ICON, FORMULA_ICON, ACTIVE_ICON,
    create_placeholder_plot # Assuming you have this or similar for error cases
)
from analytics_plot_generator import update_analytics_plots_figures
from formulas import PLOT_FORMULAS

# --- NEW CHATBOT MODULE IMPORTS ---
from chatbot_prompts import get_initial_insight_prompt_and_suggestions # MODIFIED IMPORT
from chatbot_handler import generate_llm_response
# --- END NEW CHATBOT MODULE IMPORTS ---

# Configure logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(module)s - %(message)s')


# --- Gradio UI Blocks ---
with gr.Blocks(theme=gr.themes.Soft(primary_hue="blue", secondary_hue="sky"),
               title="LinkedIn Organization Dashboard") as app:
    token_state = gr.State(value={
        "token": None, "client_id": None, "org_urn": None,
        "bubble_posts_df": pd.DataFrame(), "bubble_post_stats_df": pd.DataFrame(),
        "bubble_mentions_df": pd.DataFrame(), "bubble_follower_stats_df": pd.DataFrame(),
        "fetch_count_for_api": 0, "url_user_token_temp_storage": None,
        "config_date_col_posts": "published_at", "config_date_col_mentions": "date",
        "config_date_col_followers": "date", "config_media_type_col": "media_type",
        "config_eb_labels_col": "li_eb_label"
    })

    chat_histories_st = gr.State({})
    current_chat_plot_id_st = gr.State(None)
    plot_data_for_chatbot_st = gr.State({})

    gr.Markdown("# 🚀 LinkedIn Organization Dashboard")
    url_user_token_display = gr.Textbox(label="User Token (Nascosto)", interactive=False, visible=False)
    status_box = gr.Textbox(label="Stato Generale Token LinkedIn", interactive=False, value="Inizializzazione...")
    org_urn_display = gr.Textbox(label="URN Organizzazione (Nascosto)", interactive=False, visible=False)

    app.load(fn=get_url_user_token, inputs=None, outputs=[url_user_token_display, org_urn_display], api_name="get_url_params", show_progress=False)

    def initial_load_sequence(url_token, org_urn_val, current_state):
        status_msg, new_state, btn_update = process_and_store_bubble_token(url_token, org_urn_val, current_state)
        dashboard_content = display_main_dashboard(new_state)
        return status_msg, new_state, btn_update, dashboard_content

    with gr.Tabs() as tabs:
        with gr.TabItem("1️⃣ Dashboard & Sync", id="tab_dashboard_sync"):
            gr.Markdown("Il sistema controlla i dati esistenti da Bubble. 'Sincronizza' si attiva se sono necessari nuovi dati.")
            sync_data_btn = gr.Button("🔄 Sincronizza Dati LinkedIn", variant="primary", visible=False, interactive=False)
            sync_status_html_output = gr.HTML("<p style='text-align:center;'>Stato sincronizzazione...</p>")
            dashboard_display_html = gr.HTML("<p style='text-align:center;'>Caricamento dashboard...</p>")

            org_urn_display.change(
                fn=initial_load_sequence,
                inputs=[url_user_token_display, org_urn_display, token_state],
                outputs=[status_box, token_state, sync_data_btn, dashboard_display_html],
                show_progress="full"
            )

        with gr.TabItem("2️⃣ Analisi", id="tab_analytics"):
            gr.Markdown("## 📈 Analisi Performance LinkedIn")
            gr.Markdown("Seleziona un intervallo di date. Clicca i pulsanti (💣 Insights, ƒ Formula, 🧭 Esplora) su un grafico per azioni.")
            analytics_status_md = gr.Markdown("Stato analisi...")

            with gr.Row():
                date_filter_selector = gr.Radio(
                    ["Sempre", "Ultimi 7 Giorni", "Ultimi 30 Giorni", "Intervallo Personalizzato"],
                    label="Seleziona Intervallo Date", value="Sempre", scale=3
                )
                with gr.Column(scale=2):
                    custom_start_date_picker = gr.DateTime(label="Data Inizio", visible=False, include_time=False, type="datetime")
                    custom_end_date_picker = gr.DateTime(label="Data Fine", visible=False, include_time=False, type="datetime")

            apply_filter_btn = gr.Button("🔍 Applica Filtro & Aggiorna Analisi", variant="primary")

            def toggle_custom_date_pickers(selection):
                is_custom = selection == "Intervallo Personalizzato"
                return gr.update(visible=is_custom), gr.update(visible=is_custom)

            date_filter_selector.change(
                fn=toggle_custom_date_pickers,
                inputs=[date_filter_selector],
                outputs=[custom_start_date_picker, custom_end_date_picker]
            )

            plot_configs = [
                {"label": "Numero di Follower nel Tempo", "id": "followers_count", "section": "Dinamiche dei Follower"},
                {"label": "Tasso di Crescita Follower", "id": "followers_growth_rate", "section": "Dinamiche dei Follower"},
                {"label": "Follower per Località", "id": "followers_by_location", "section": "Demografia Follower"},
                {"label": "Follower per Ruolo (Funzione)", "id": "followers_by_role", "section": "Demografia Follower"},
                {"label": "Follower per Settore", "id": "followers_by_industry", "section": "Demografia Follower"},
                {"label": "Follower per Anzianità", "id": "followers_by_seniority", "section": "Demografia Follower"},
                {"label": "Tasso di Engagement nel Tempo", "id": "engagement_rate", "section": "Approfondimenti Performance Post"},
                {"label": "Copertura nel Tempo", "id": "reach_over_time", "section": "Approfondimenti Performance Post"},
                {"label": "Visualizzazioni nel Tempo", "id": "impressions_over_time", "section": "Approfondimenti Performance Post"},
                {"label": "Reazioni (Like) nel Tempo", "id": "likes_over_time", "section": "Approfondimenti Performance Post"},
                {"label": "Click nel Tempo", "id": "clicks_over_time", "section": "Engagement Dettagliato Post nel Tempo"},
                {"label": "Condivisioni nel Tempo", "id": "shares_over_time", "section": "Engagement Dettagliato Post nel Tempo"},
                {"label": "Commenti nel Tempo", "id": "comments_over_time", "section": "Engagement Dettagliato Post nel Tempo"},
                {"label": "Ripartizione Commenti per Sentiment", "id": "comments_sentiment", "section": "Engagement Dettagliato Post nel Tempo"},
                {"label": "Frequenza Post", "id": "post_frequency_cs", "section": "Analisi Strategia Contenuti"},
                {"label": "Ripartizione Contenuti per Formato", "id": "content_format_breakdown_cs", "section": "Analisi Strategia Contenuti"},
                {"label": "Ripartizione Contenuti per Argomenti", "id": "content_topic_breakdown_cs", "section": "Analisi Strategia Contenuti"},
                {"label": "Volume Menzioni nel Tempo (Dettaglio)", "id": "mention_analysis_volume", "section": "Analisi Menzioni (Dettaglio)"},
                {"label": "Ripartizione Menzioni per Sentiment (Dettaglio)", "id": "mention_analysis_sentiment", "section": "Analisi Menzioni (Dettaglio)"}
            ]
            assert len(plot_configs) == 19, "Mancata corrispondenza in plot_configs e grafici attesi."

            active_panel_action_state = gr.State(None)
            explored_plot_id_state = gr.State(None)

            plot_ui_objects = {}

            with gr.Row(equal_height=False):
                with gr.Column(scale=8) as plots_area_col:
                    plot_ui_objects = build_analytics_tab_plot_area(plot_configs)

                with gr.Column(scale=4, visible=False) as global_actions_column_ui:
                    gr.Markdown("### 💡 Azioni Contestuali Grafico")
                    insights_chatbot_ui = gr.Chatbot(
                        label="Chat Insights", type="messages", height=450,
                        bubble_full_width=False, visible=False, show_label=False,
                        placeholder="L'analisi AI del grafico apparirà qui. Fai domande di approfondimento!"
                    )
                    insights_chat_input_ui = gr.Textbox(
                        label="La tua domanda:", placeholder="Chiedi all'AI riguardo a questo grafico...",
                        lines=2, visible=False, show_label=False
                    )
                    with gr.Row(visible=False) as insights_suggestions_row_ui:
                        insights_suggestion_1_btn = gr.Button(value="Suggerimento 1", size="sm", min_width=50)
                        insights_suggestion_2_btn = gr.Button(value="Suggerimento 2", size="sm", min_width=50)
                        insights_suggestion_3_btn = gr.Button(value="Suggerimento 3", size="sm", min_width=50)

                    formula_display_markdown_ui = gr.Markdown(
                        "I dettagli sulla formula/metodologia appariranno qui.", visible=False
                    )

            async def handle_panel_action(
                plot_id_clicked: str,
                action_type: str, # "insights" or "formula"
                current_active_action_from_state: dict,
                current_chat_histories: dict,
                current_chat_plot_id: str,
                current_plot_data_for_chatbot: dict,
                current_explored_plot_id: str # NEW: Current explore state
            ):
                logging.info(f"Azione '{action_type}' per grafico: {plot_id_clicked}. Attualmente attivo: {current_active_action_from_state}, Esplorato: {current_explored_plot_id}")

                clicked_plot_config = next((p for p in plot_configs if p["id"] == plot_id_clicked), None)
                if not clicked_plot_config:
                    logging.error(f"Configurazione non trovata per plot_id {plot_id_clicked}")
                    num_plots = len(plot_configs)
                    error_output_list = [
                        gr.update(visible=False), gr.update(visible=False), gr.update(value=[]),
                        gr.update(visible=False), gr.update(visible=False), gr.update(), gr.update(), gr.update(),
                        gr.update(visible=False), gr.update(value=""),
                        current_active_action_from_state, current_chat_plot_id, current_chat_histories,
                        current_explored_plot_id # Pass back existing explore state
                    ]
                    error_output_list.extend([gr.update()] * num_plots)  # Panel vis
                    error_output_list.extend([gr.update()] * (2 * num_plots))  # Bomb, Formula icons
                    error_output_list.extend([gr.update()] * num_plots)  # Explore icons
                    return error_output_list

                clicked_plot_label = clicked_plot_config["label"]
                hypothetical_new_active_state = {"plot_id": plot_id_clicked, "type": action_type}
                is_toggling_off = current_active_action_from_state == hypothetical_new_active_state

                # Initialize updates
                action_col_visible_update = gr.update(visible=False)
                insights_chatbot_visible_update = gr.update(visible=False)
                insights_chat_input_visible_update = gr.update(visible=False)
                insights_suggestions_row_visible_update = gr.update(visible=False)
                formula_display_visible_update = gr.update(visible=False)
                chatbot_content_update = gr.update()
                suggestion_1_update, suggestion_2_update, suggestion_3_update = gr.update(), gr.update(), gr.update()
                formula_content_update = gr.update()
                
                new_active_action_state_to_set = None
                new_current_chat_plot_id = current_chat_plot_id
                updated_chat_histories = current_chat_histories
                new_explored_plot_id_to_set = current_explored_plot_id # Default to not changing explore state

                panel_visibility_component_updates = []
                action_button_component_updates = [] # For bomb and formula buttons
                explore_button_component_updates = []


                if is_toggling_off:
                    new_active_action_state_to_set = None
                    action_col_visible_update = gr.update(visible=False)
                    # new_explored_plot_id_to_set remains current_explored_plot_id
                    
                    logging.info(f"Chiusura pannello {action_type} per {plot_id_clicked}.")
                    if current_explored_plot_id: # If an explore view is active, keep it
                        for cfg_item_iter in plot_configs:
                            p_id_iter = cfg_item_iter["id"]
                            is_explored = (p_id_iter == current_explored_plot_id)
                            panel_visibility_component_updates.append(gr.update(visible=is_explored))
                            explore_button_component_updates.append(gr.update(value=ACTIVE_ICON if is_explored else EXPLORE_ICON))
                    else: # No explore active, make all plots visible
                        for _ in plot_configs:
                            panel_visibility_component_updates.append(gr.update(visible=True))
                            explore_button_component_updates.append(gr.update(value=EXPLORE_ICON))
                    
                    # Reset bomb/formula icons for all plots to default
                    for _ in plot_configs:
                        action_button_component_updates.append(gr.update(value=BOMB_ICON))
                        action_button_component_updates.append(gr.update(value=FORMULA_ICON))
                    
                    if action_type == "insights": new_current_chat_plot_id = None

                else: # Opening a new panel or switching
                    new_active_action_state_to_set = hypothetical_new_active_state
                    action_col_visible_update = gr.update(visible=True)
                    
                    # IMPORTANT: Cancel any active explore view when opening insight/formula
                    new_explored_plot_id_to_set = None 
                    
                    logging.info(f"Apertura pannello {action_type} per {plot_id_clicked}. Solo questo grafico visibile. Esplorazione annullata.")

                    for cfg_item_iter in plot_configs:
                        p_id_iter = cfg_item_iter["id"]
                        is_target_plot = (p_id_iter == plot_id_clicked)
                        panel_visibility_component_updates.append(gr.update(visible=is_target_plot))
                        # Reset all explore buttons to default as explore is cancelled
                        explore_button_component_updates.append(gr.update(value=EXPLORE_ICON))

                    # Set active icons for the clicked plot's bomb/formula buttons
                    for cfg_item_btn_iter in plot_configs:
                        p_id_btn_iter = cfg_item_btn_iter["id"]
                        is_active_insights = new_active_action_state_to_set == {"plot_id": p_id_btn_iter, "type": "insights"}
                        is_active_formula = new_active_action_state_to_set == {"plot_id": p_id_btn_iter, "type": "formula"}
                        action_button_component_updates.append(gr.update(value=ACTIVE_ICON if is_active_insights else BOMB_ICON))
                        action_button_component_updates.append(gr.update(value=ACTIVE_ICON if is_active_formula else FORMULA_ICON))

                    if action_type == "insights":
                        insights_chatbot_visible_update = gr.update(visible=True)
                        insights_chat_input_visible_update = gr.update(visible=True)
                        insights_suggestions_row_visible_update = gr.update(visible=True)
                        new_current_chat_plot_id = plot_id_clicked
                        chat_history_for_this_plot = current_chat_histories.get(plot_id_clicked, [])
                        plot_specific_data_summary = current_plot_data_for_chatbot.get(plot_id_clicked, f"Nessun sommario dati specifico disponibile per '{clicked_plot_label}'.")

                        if not chat_history_for_this_plot:
                            initial_llm_prompt, suggestions = get_initial_insight_prompt_and_suggestions(
                                plot_id_clicked, clicked_plot_label, plot_specific_data_summary
                            )
                            history_for_llm_first_turn = [{"role": "user", "content": initial_llm_prompt}]
                            initial_bot_response_text = await generate_llm_response(
                                initial_llm_prompt, plot_id_clicked, clicked_plot_label,
                                history_for_llm_first_turn, plot_specific_data_summary
                            )
                            chat_history_for_this_plot = [{"role": "assistant", "content": initial_bot_response_text}]
                            updated_chat_histories = current_chat_histories.copy()
                            updated_chat_histories[plot_id_clicked] = chat_history_for_this_plot
                        else:
                            _, suggestions = get_initial_insight_prompt_and_suggestions(
                                plot_id_clicked, clicked_plot_label, plot_specific_data_summary
                            )
                        
                        chatbot_content_update = gr.update(value=chat_history_for_this_plot)
                        suggestion_1_update = gr.update(value=suggestions[0] if len(suggestions) > 0 else "N/A")
                        suggestion_2_update = gr.update(value=suggestions[1] if len(suggestions) > 1 else "N/A")
                        suggestion_3_update = gr.update(value=suggestions[2] if len(suggestions) > 2 else "N/A")

                    elif action_type == "formula":
                        formula_display_visible_update = gr.update(visible=True)
                        formula_key = PLOT_ID_TO_FORMULA_KEY_MAP.get(plot_id_clicked)
                        formula_text = f"**Formula/Metodologia per: {clicked_plot_label}**\n\nID Grafico: `{plot_id_clicked}`.\n\n"
                        if formula_key and formula_key in PLOT_FORMULAS:
                            formula_data = PLOT_FORMULAS[formula_key]
                            formula_text += f"### {formula_data['title']}\n\n{formula_data['description']}\n\n**Come viene calcolato:**\n"
                            formula_text += "\n".join([f"- {step}" for step in formula_data['calculation_steps']])
                        else:
                            formula_text += "(Nessuna informazione dettagliata sulla formula trovata)"
                        formula_content_update = gr.update(value=formula_text)
                        new_current_chat_plot_id = None # Ensure chat is cleared if formula is opened

                final_updates = [
                    action_col_visible_update,
                    insights_chatbot_visible_update, chatbot_content_update,
                    insights_chat_input_visible_update,
                    insights_suggestions_row_visible_update, suggestion_1_update, suggestion_2_update, suggestion_3_update,
                    formula_display_visible_update, formula_content_update,
                    new_active_action_state_to_set,
                    new_current_chat_plot_id,
                    updated_chat_histories,
                    new_explored_plot_id_to_set # NEW: update explored_plot_id_state
                ]
                final_updates.extend(panel_visibility_component_updates)
                final_updates.extend(action_button_component_updates)
                final_updates.extend(explore_button_component_updates)
                
                return final_updates

            async def handle_chat_message_submission(
                user_message: str,
                current_plot_id: str,
                chat_histories: dict,
                current_plot_data_for_chatbot: dict
            ):
                if not current_plot_id or not user_message.strip():
                    history_for_plot = chat_histories.get(current_plot_id, [])
                    yield history_for_plot, gr.update(value=""), chat_histories
                    return

                plot_config = next((p for p in plot_configs if p["id"] == current_plot_id), None)
                plot_label = plot_config["label"] if plot_config else "Grafico Selezionato"
                plot_specific_data_summary = current_plot_data_for_chatbot.get(current_plot_id, f"Nessun sommario dati specifico disponibile per '{plot_label}'.")
                history_for_plot = chat_histories.get(current_plot_id, []).copy()
                history_for_plot.append({"role": "user", "content": user_message})
                yield history_for_plot, gr.update(value=""), chat_histories

                bot_response_text = await generate_llm_response(
                    user_message, current_plot_id, plot_label, history_for_plot, plot_specific_data_summary
                )
                history_for_plot.append({"role": "assistant", "content": bot_response_text})
                updated_chat_histories = chat_histories.copy()
                updated_chat_histories[current_plot_id] = history_for_plot
                yield history_for_plot, "", updated_chat_histories

            async def handle_suggested_question_click(
                suggestion_text: str,
                current_plot_id: str,
                chat_histories: dict,
                current_plot_data_for_chatbot: dict
            ):
                if not current_plot_id or not suggestion_text.strip():
                    history_for_plot = chat_histories.get(current_plot_id, [])
                    yield history_for_plot, gr.update(value=""), chat_histories
                    return
                async for update in handle_chat_message_submission(
                    suggestion_text, current_plot_id, chat_histories, current_plot_data_for_chatbot
                ):
                    yield update

            def handle_explore_click(
                plot_id_clicked, 
                current_explored_plot_id_from_state,
                current_active_panel_action_state # NEW: current insight/formula state
            ):
                logging.info(f"Click su Esplora per: {plot_id_clicked}. Attualmente esplorato: {current_explored_plot_id_from_state}. Pannello Azioni Attivo: {current_active_panel_action_state}")
                if not plot_ui_objects:
                    logging.error("plot_ui_objects non popolato durante handle_explore_click.")
                    num_plots = len(plot_configs)
                    error_updates = [current_explored_plot_id_from_state, gr.update(visible=False), current_active_panel_action_state]
                    error_updates.extend([gr.update()] * num_plots) # Panel vis
                    error_updates.extend([gr.update()] * num_plots) # Explore icons
                    error_updates.extend([gr.update()] * (2 * num_plots)) # Bomb, Formula icons
                    return error_updates

                new_explored_id_to_set = None
                is_toggling_off_explore = (plot_id_clicked == current_explored_plot_id_from_state)

                action_col_update = gr.update() 
                new_active_panel_action_state_update = current_active_panel_action_state
                
                panel_vis_updates = []
                explore_btn_updates = []
                bomb_btn_icon_upds = []
                formula_btn_icon_upds = []

                if is_toggling_off_explore:
                    new_explored_id_to_set = None
                    logging.info(f"Interruzione esplorazione grafico: {plot_id_clicked}. Tutti i grafici diventano visibili.")
                    # All plots become visible
                    for _ in plot_configs:
                        panel_vis_updates.append(gr.update(visible=True))
                        explore_btn_updates.append(gr.update(value=EXPLORE_ICON))
                    # Insight/formula buttons remain as they were (no change)
                    for _ in plot_configs:
                        bomb_btn_icon_upds.append(gr.update())
                        formula_btn_icon_upds.append(gr.update())
                else: # Activating explore for plot_id_clicked or switching explore
                    new_explored_id_to_set = plot_id_clicked
                    logging.info(f"Esplorazione grafico: {plot_id_clicked}. Altri grafici nascosti.")
                    # Make only explored plot visible
                    for cfg in plot_configs:
                        p_id = cfg["id"]
                        is_target_plot = (p_id == new_explored_id_to_set)
                        panel_vis_updates.append(gr.update(visible=is_target_plot))
                        explore_btn_updates.append(gr.update(value=ACTIVE_ICON if is_target_plot else EXPLORE_ICON))
                    
                    # If activating explore, close any active insight/formula panel
                    if current_active_panel_action_state:
                        logging.info("Chiusura pannello azioni (insight/formula) a causa dell'attivazione dell'esplorazione.")
                        action_col_update = gr.update(visible=False)
                        new_active_panel_action_state_update = None
                        # Reset all insight/formula button icons
                        for _ in plot_configs:
                            bomb_btn_icon_upds.append(gr.update(value=BOMB_ICON))
                            formula_btn_icon_upds.append(gr.update(value=FORMULA_ICON))
                    else: # No insight/formula panel active, no change to their buttons
                         for _ in plot_configs:
                            bomb_btn_icon_upds.append(gr.update())
                            formula_btn_icon_upds.append(gr.update())
                
                final_updates = [
                    new_explored_id_to_set,
                    action_col_update,
                    new_active_panel_action_state_update
                ]
                final_updates.extend(panel_vis_updates)
                final_updates.extend(explore_btn_updates)
                final_updates.extend(bomb_btn_icon_upds)
                final_updates.extend(formula_btn_icon_upds)
                return final_updates

            # --- Define Output Lists for Event Handlers ---
            action_panel_outputs_list = [
                global_actions_column_ui,
                insights_chatbot_ui, insights_chatbot_ui, 
                insights_chat_input_ui,
                insights_suggestions_row_ui, insights_suggestion_1_btn, insights_suggestion_2_btn, insights_suggestion_3_btn,
                formula_display_markdown_ui, formula_display_markdown_ui,
                active_panel_action_state,
                current_chat_plot_id_st,
                chat_histories_st,
                explored_plot_id_state # NEW: output for explore state
            ]
            for cfg_item_action_out in plot_configs:
                pid_action_out = cfg_item_action_out["id"]
                ui_obj_ref = plot_ui_objects.get(pid_action_out)
                action_panel_outputs_list.append(ui_obj_ref["panel_component"] if ui_obj_ref else gr.update()) # Panel visibility
            for cfg_item_action_out in plot_configs:
                pid_action_out = cfg_item_action_out["id"]
                ui_obj_ref = plot_ui_objects.get(pid_action_out)
                action_panel_outputs_list.append(ui_obj_ref["bomb_button"] if ui_obj_ref else gr.update())    # Bomb icon
                action_panel_outputs_list.append(ui_obj_ref["formula_button"] if ui_obj_ref else gr.update()) # Formula icon
            for cfg_item_action_out in plot_configs:
                pid_action_out = cfg_item_action_out["id"]
                ui_obj_ref = plot_ui_objects.get(pid_action_out)
                action_panel_outputs_list.append(ui_obj_ref["explore_button"] if ui_obj_ref else gr.update()) # Explore icon

            explore_outputs_list = [
                explored_plot_id_state,
                global_actions_column_ui, # NEW: output for action column
                active_panel_action_state # NEW: output for active panel state
            ]
            for cfg_item_explore_out in plot_configs: # Panel visibility
                pid_explore_out = cfg_item_explore_out["id"]
                ui_obj_ref = plot_ui_objects.get(pid_explore_out)
                explore_outputs_list.append(ui_obj_ref["panel_component"] if ui_obj_ref else gr.update())
            for cfg_item_explore_out in plot_configs: # Explore button icons
                pid_explore_out = cfg_item_explore_out["id"]
                ui_obj_ref = plot_ui_objects.get(pid_explore_out)
                explore_outputs_list.append(ui_obj_ref["explore_button"] if ui_obj_ref else gr.update())
            for cfg_item_explore_out in plot_configs: # Bomb button icons
                pid_explore_out = cfg_item_explore_out["id"]
                ui_obj_ref = plot_ui_objects.get(pid_explore_out)
                explore_outputs_list.append(ui_obj_ref["bomb_button"] if ui_obj_ref else gr.update())
            for cfg_item_explore_out in plot_configs: # Formula button icons
                pid_explore_out = cfg_item_explore_out["id"]
                ui_obj_ref = plot_ui_objects.get(pid_explore_out)
                explore_outputs_list.append(ui_obj_ref["formula_button"] if ui_obj_ref else gr.update())


            # --- Define Input Lists for Event Handlers ---
            action_click_inputs = [
                active_panel_action_state,
                chat_histories_st,
                current_chat_plot_id_st,
                plot_data_for_chatbot_st,
                explored_plot_id_state # NEW: input explore state
            ]
            explore_click_inputs = [
                explored_plot_id_state,
                active_panel_action_state # NEW: input active panel state
            ]

            # --- Register Event Handlers ---
            def create_panel_action_handler(p_id, action_type_str):
                async def _handler(current_active_val, current_chats_val, current_chat_pid, current_plot_data_summaries, current_explored_id_val): # Added current_explored_id_val
                    logging.debug(f"Entering _handler for plot_id: {p_id}, action: {action_type_str}")
                    result = await handle_panel_action(p_id, action_type_str, current_active_val, current_chats_val, current_chat_pid, current_plot_data_summaries, current_explored_id_val) # Pass current_explored_id_val
                    logging.debug(f"_handler for plot_id: {p_id}, action: {action_type_str} completed with {len(result)} updates.")
                    return result
                return _handler

            for config_item in plot_configs:
                plot_id = config_item["id"]
                if plot_id in plot_ui_objects:
                    ui_obj = plot_ui_objects[plot_id]
                    ui_obj["bomb_button"].click(
                        fn=create_panel_action_handler(plot_id, "insights"),
                        inputs=action_click_inputs,
                        outputs=action_panel_outputs_list,
                        api_name=f"action_insights_{plot_id}"
                    )
                    ui_obj["formula_button"].click(
                        fn=create_panel_action_handler(plot_id, "formula"),
                        inputs=action_click_inputs,
                        outputs=action_panel_outputs_list,
                        api_name=f"action_formula_{plot_id}"
                    )
                    ui_obj["explore_button"].click(
                        fn=lambda current_explored_val, current_active_panel_val, p_id=plot_id: handle_explore_click(p_id, current_explored_val, current_active_panel_val),
                        inputs=explore_click_inputs, # Uses updated explore_click_inputs
                        outputs=explore_outputs_list, # Uses updated explore_outputs_list
                        api_name=f"action_explore_{plot_id}"
                    )
                else:
                    logging.warning(f"Oggetto UI per plot_id '{plot_id}' non trovato durante il tentativo di associare i gestori di click.")

            chat_submission_outputs = [insights_chatbot_ui, insights_chat_input_ui, chat_histories_st]
            chat_submission_inputs = [insights_chat_input_ui, current_chat_plot_id_st, chat_histories_st, plot_data_for_chatbot_st]

            insights_chat_input_ui.submit(
                fn=handle_chat_message_submission,
                inputs=chat_submission_inputs,
                outputs=chat_submission_outputs,
                api_name="submit_chat_message"
            )

            suggestion_click_inputs = [current_chat_plot_id_st, chat_histories_st, plot_data_for_chatbot_st]
            insights_suggestion_1_btn.click(
                fn=handle_suggested_question_click,
                inputs=[insights_suggestion_1_btn] + suggestion_click_inputs,
                outputs=chat_submission_outputs, api_name="click_suggestion_1"
            )
            insights_suggestion_2_btn.click(
                fn=handle_suggested_question_click,
                inputs=[insights_suggestion_2_btn] + suggestion_click_inputs,
                outputs=chat_submission_outputs, api_name="click_suggestion_2"
            )
            insights_suggestion_3_btn.click(
                fn=handle_suggested_question_click,
                inputs=[insights_suggestion_3_btn] + suggestion_click_inputs,
                outputs=chat_submission_outputs, api_name="click_suggestion_3"
            )

            def refresh_all_analytics_ui_elements(current_token_state, date_filter_val, custom_start_val, custom_end_val, current_chat_histories):
                logging.info("Aggiornamento di tutti gli elementi UI delle analisi e reset delle azioni/chat.")
                plot_generation_results = update_analytics_plots_figures(
                    current_token_state, date_filter_val, custom_start_val, custom_end_val, plot_configs
                )
                status_message_update = plot_generation_results[0]
                generated_plot_figures = plot_generation_results[1:-1]
                new_plot_data_summaries = plot_generation_results[-1]

                all_updates = [status_message_update]
                for i in range(len(plot_configs)):
                    if i < len(generated_plot_figures):
                        all_updates.append(generated_plot_figures[i])
                    else:
                        # Ensure create_placeholder_plot is defined or handle appropriately
                        all_updates.append(create_placeholder_plot("Errore Figura", f"Figura mancante per grafico {plot_configs[i]['id']}"))
                
                all_updates.extend([
                    gr.update(visible=False), # global_actions_column_ui
                    gr.update(value=[], visible=False), # insights_chatbot_ui
                    gr.update(value="", visible=False), # insights_chat_input_ui
                    gr.update(visible=False), # insights_suggestions_row_ui
                    gr.update(value="Suggerimento 1"), gr.update(value="Suggerimento 2"), gr.update(value="Suggerimento 3"),
                    gr.update(value="I dettagli sulla formula/metodologia appariranno qui.", visible=False), # formula_display_markdown_ui
                    None, # active_panel_action_state
                    None, # current_chat_plot_id_st
                    {},   # chat_histories_st (reset)
                    new_plot_data_summaries # plot_data_for_chatbot_st
                ])

                for cfg in plot_configs:
                    pid = cfg["id"]
                    # Reset button icons
                    all_updates.append(gr.update(value=BOMB_ICON))
                    all_updates.append(gr.update(value=FORMULA_ICON))
                    all_updates.append(gr.update(value=EXPLORE_ICON))
                    # Make all plot panels visible
                    all_updates.append(gr.update(visible=True)) # panel_component visibility
                
                all_updates.append(None) # explored_plot_id_state (reset)
                logging.info(f"Preparati {len(all_updates)} aggiornamenti per il refresh delle analisi.")
                return all_updates

            apply_filter_and_sync_outputs_list = [analytics_status_md]
            for config_item_filter_sync in plot_configs: # Plot components
                pid = config_item_filter_sync["id"]
                apply_filter_and_sync_outputs_list.append(plot_ui_objects[pid]["plot_component"] if pid in plot_ui_objects and "plot_component" in plot_ui_objects[pid] else gr.update())
            
            apply_filter_and_sync_outputs_list.extend([ # UI elements to reset
                global_actions_column_ui, insights_chatbot_ui, insights_chat_input_ui,
                insights_suggestions_row_ui, insights_suggestion_1_btn, insights_suggestion_2_btn, insights_suggestion_3_btn,
                formula_display_markdown_ui,
                active_panel_action_state, current_chat_plot_id_st, chat_histories_st,
                plot_data_for_chatbot_st
            ])
            for cfg_filter_sync_btns in plot_configs: # Button icons and panel visibility
                pid = cfg_filter_sync_btns["id"]
                apply_filter_and_sync_outputs_list.append(plot_ui_objects[pid]["bomb_button"] if pid in plot_ui_objects else gr.update())
                apply_filter_and_sync_outputs_list.append(plot_ui_objects[pid]["formula_button"] if pid in plot_ui_objects else gr.update())
                apply_filter_and_sync_outputs_list.append(plot_ui_objects[pid]["explore_button"] if pid in plot_ui_objects else gr.update())
                apply_filter_and_sync_outputs_list.append(plot_ui_objects[pid]["panel_component"] if pid in plot_ui_objects else gr.update())
            
            apply_filter_and_sync_outputs_list.append(explored_plot_id_state) # Reset explored state
            
            apply_filter_btn.click(
                fn=refresh_all_analytics_ui_elements,
                inputs=[token_state, date_filter_selector, custom_start_date_picker, custom_end_date_picker, chat_histories_st],
                outputs=apply_filter_and_sync_outputs_list,
                show_progress="full"
            )

        with gr.TabItem("3️⃣ Menzioni", id="tab_mentions"):
            refresh_mentions_display_btn = gr.Button("🔄 Aggiorna Visualizzazione Menzioni", variant="secondary")
            mentions_html = gr.HTML("Dati menzioni...")
            mentions_sentiment_dist_plot = gr.Plot(label="Distribuzione Sentiment Menzioni")
            refresh_mentions_display_btn.click(
                fn=run_mentions_tab_display, inputs=[token_state],
                outputs=[mentions_html, mentions_sentiment_dist_plot],
                show_progress="full"
            )

        with gr.TabItem("4️⃣ Statistiche Follower", id="tab_follower_stats"):
            refresh_follower_stats_btn = gr.Button("🔄 Aggiorna Visualizzazione Statistiche Follower", variant="secondary")
            follower_stats_html = gr.HTML("Statistiche follower...")
            with gr.Row():
                fs_plot_monthly_gains = gr.Plot(label="Guadagni Mensili Follower")
            with gr.Row():
                fs_plot_seniority = gr.Plot(label="Follower per Anzianità (Top 10 Organici)")
                fs_plot_industry = gr.Plot(label="Follower per Settore (Top 10 Organici)")
            
            refresh_follower_stats_btn.click(
                fn=run_follower_stats_tab_display, inputs=[token_state],
                outputs=[follower_stats_html, fs_plot_monthly_gains, fs_plot_seniority, fs_plot_industry],
                show_progress="full"
            )
            
    sync_event_part1 = sync_data_btn.click(
        fn=sync_all_linkedin_data_orchestrator,
        inputs=[token_state], outputs=[sync_status_html_output, token_state], show_progress="full"
    )
    sync_event_part2 = sync_event_part1.then(
        fn=process_and_store_bubble_token,
        inputs=[url_user_token_display, org_urn_display, token_state],
        outputs=[status_box, token_state, sync_data_btn], show_progress=False
    )
    sync_event_part3 = sync_event_part2.then(
        fn=display_main_dashboard,
        inputs=[token_state], outputs=[dashboard_display_html], show_progress=False
    )
    sync_event_final = sync_event_part3.then(
        fn=refresh_all_analytics_ui_elements, 
        inputs=[token_state, date_filter_selector, custom_start_date_picker, custom_end_date_picker, chat_histories_st],
        outputs=apply_filter_and_sync_outputs_list,
        show_progress="full"
    )

if __name__ == "__main__":
    if not os.environ.get(LINKEDIN_CLIENT_ID_ENV_VAR):
        logging.warning(f"ATTENZIONE: Variabile d'ambiente '{LINKEDIN_CLIENT_ID_ENV_VAR}' non impostata.")
    if not os.environ.get(BUBBLE_APP_NAME_ENV_VAR) or \
       not os.environ.get(BUBBLE_API_KEY_PRIVATE_ENV_VAR) or \
       not os.environ.get(BUBBLE_API_ENDPOINT_ENV_VAR):
        logging.warning("ATTENZIONE: Variabili d'ambiente Bubble non completamente impostate.")
    
    try:
        logging.info(f"Versione Matplotlib: {matplotlib.__version__}, Backend: {matplotlib.get_backend()}")
    except ImportError:
        logging.warning("Matplotlib non trovato direttamente, ma potrebbe essere usato dai generatori di grafici.")
        
    app.launch(server_name="0.0.0.0", server_port=7860, debug=True)