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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
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
import streamlit as st
import pandas as pd
import numpy as np
import plotly.express as px
import plotly.graph_objects as go
from scipy import stats
import io
import base64
from datetime import datetime

def show():
    st.header("🔍 Analizador Avanzado de Datos")
    
    # =============================================================================
    # USAR DATOS GLOBALES DEL CONVERSOR - ELIMINADA CARGA DUPLICADA
    # =============================================================================
    
    # Verificar si hay datos globales cargados desde el conversor
    if st.session_state.get('global_df') is None:
        st.warning("⚠️ No hay datos cargados en el sistema.")
        st.info("💡 Por favor, carga un archivo en la barra lateral del conversor para comenzar el análisis.")
        
        # Mostrar información adicional para ayudar al usuario
        with st.expander("¿Cómo cargar datos?", expanded=False):
            st.markdown("""
            **Pasos para cargar datos:**
            1. Ve a la barra lateral izquierda
            2. En la sección **'📁 Carga Global de Datos'**
            3. Haz clic en **'Sube tu archivo de datos'**
            4. Selecciona tu archivo CSV, Excel o JSON
            5. ¡Los datos estarán disponibles en todos los módulos!
            
            **Formatos soportados:** CSV, XLSX, XLS, JSON, DB, SQLITE, SQL
            """)
        return
    
    # Usar datos globales del conversor
    df = st.session_state.global_df.copy()
    filename = st.session_state.global_filename
    
    st.success(f"✅ Analizando: **{filename}** - Datos cargados desde el sistema global")
    
    # =============================================================================
    # DETECCIÓN AUTOMÁTICA DE TIPOS DE DATOS - MEJORADA
    # =============================================================================
    
    # Aplicar conversión automática de tipos si no se ha hecho
    df = auto_detect_and_convert_dtypes_improved(df)
    
    # Mostrar resumen de tipos de datos
    numeric_cols = df.select_dtypes(include=[np.number]).columns.tolist()
    date_cols = df.select_dtypes(include=['datetime64']).columns.tolist()
    categorical_cols = df.select_dtypes(include=['object', 'category']).columns.tolist()
    
    col1, col2, col3 = st.columns(3)
    with col1:
        st.metric("Columnas Numéricas", len(numeric_cols))
    with col2:
        st.metric("Columnas Fecha", len(date_cols))
    with col3:
        st.metric("Columnas Texto", len(categorical_cols))
    
    # =============================================================================
    # PANEL DE CONTROL PRINCIPAL MEJORADO (MANTENIDO)
    # =============================================================================
    st.subheader("🎛️ Panel de Control del Análisis")
    
    control_col1, control_col2, control_col3 = st.columns(3)
    
    with control_col1:
        analysis_type = st.selectbox(
            "Tipo de Análisis:",
            ["📊 Análisis General", "🎯 Análisis por Columnas", "🔗 Análisis de Correlaciones", 
             "📅 Análisis Temporal", "🎯 Detección de Outliers", "📈 Análisis de Distribución",
             "⚠️ Análisis de Calidad", "🔧 Conversor de Datos"]
        )
    
    with control_col2:
        if analysis_type == "🎯 Análisis por Columnas":
            selected_columns = st.multiselect(
                "Seleccionar columnas:",
                df.columns.tolist(),
                default=df.columns.tolist()[:3] if len(df.columns) >= 3 else df.columns.tolist()
            )
        else:
            selected_columns = df.columns.tolist()
    
    with control_col3:
        if len(df) > 100:
            sample_size = st.slider("Tamaño de muestra:", 100, len(df), min(1000, len(df)))
        else:
            sample_size = len(df)
            st.info(f"📊 Muestra completa: {len(df)} filas")
        
        # Botón para recargar datos originales
        if st.button("🔄 Recargar Datos Originales"):
            if 'global_df' in st.session_state:
                st.session_state.df = st.session_state.global_df.copy()
                if 'quality_changes' in st.session_state:
                    st.session_state.quality_changes = []
                st.success("Datos originales restaurados")
                st.rerun()
    
    # =============================================================================
    # ANÁLISIS CON DETECCIÓN MEJORADA (MANTENIDO)
    # =============================================================================
    
    if analysis_type == "📊 Análisis General":
        show_general_analysis(df, sample_size)
    
    elif analysis_type == "🎯 Análisis por Columnas":
        show_column_analysis_improved(df, selected_columns, sample_size)
    
    elif analysis_type == "🔗 Análisis de Correlaciones":
        show_correlation_analysis_improved(df, sample_size)
    
    elif analysis_type == "📅 Análisis Temporal":
        show_temporal_analysis_improved(df, sample_size)
    
    elif analysis_type == "🎯 Detección de Outliers":
        show_outliers_analysis_improved(df, sample_size)
    
    elif analysis_type == "📈 Análisis de Distribución":
        show_distribution_analysis_improved(df, sample_size)
    
    elif analysis_type == "⚠️ Análisis de Calidad":
        show_quality_analysis_improved(df)
    
    elif analysis_type == "🔧 Conversor de Datos":
        show_data_converter(df)

# =============================================================================
# FUNCIÓN DE CONVERSIÓN AUTOMÁTICA DE TIPOS DE DATOS - MEJORADA
# =============================================================================

def auto_detect_and_convert_dtypes_improved(df):
    """Convierte automáticamente los tipos de datos al cargar el archivo - VERSIÓN MEJORADA"""
    new_df = df.copy()
    
    for col in new_df.columns:
        # Intentar convertir a numérico
        numeric_converted = pd.to_numeric(new_df[col], errors='coerce')
        if numeric_converted.notna().sum() > len(new_df) * 0.8:  # Si >80% se convierte
            new_df[col] = numeric_converted
            
            # MEJORA: Detectar timestamps grandes y convertirlos a fechas
            if new_df[col].dtype in [np.int64, np.float64]:
                sample_value = new_df[col].dropna().iloc[0] if not new_df[col].dropna().empty else 0
                if abs(sample_value) > 1e10:  # Posible timestamp
                    try:
                        # Intentar convertir timestamps a fechas
                        if abs(sample_value) > 1e12:  # Probablemente nanosegundos
                            timestamps = new_df[col] / 1000000  # Convertir a milisegundos
                        else:
                            timestamps = new_df[col]
                        
                        dates = pd.to_datetime(timestamps, unit='ms', errors='coerce')
                        if dates.notna().sum() > len(new_df) * 0.8:  # Si >80% se convierte
                            new_df[col] = dates
                    except:
                        pass
            continue
        
        # Intentar convertir a fecha
        date_converted = pd.to_datetime(new_df[col], errors='coerce')
        if date_converted.notna().sum() > len(new_df) * 0.8:  # Si >80% se convierte
            new_df[col] = date_converted
            continue
        
        # Si es booleano (1/0, True/False, Sí/No)
        if new_df[col].dtype == 'object':
            unique_vals = new_df[col].astype(str).str.lower().unique()
            if set(unique_vals).issubset({'0', '1', 'true', 'false', 'yes', 'no', 'sí', 'no', 'verdadero', 'falso'}):
                new_df[col] = new_df[col].astype(str).str.lower().map({
                    '1': True, 'true': True, 'yes': True, 'sí': True, 'verdadero': True,
                    '0': False, 'false': False, 'no': False, 'falso': False
                })
    
    return new_df

# =============================================================================
# FUNCIONES DE DETECCIÓN Y CONVERSIÓN MEJORADAS (MANTENIDAS)
# =============================================================================

def detect_potential_numeric_columns(df):
    """Detecta columnas que podrían convertirse a numérico"""
    potential_numeric = []
    
    for col in df.columns:
        # Saltar columnas que ya son numéricas
        if pd.api.types.is_numeric_dtype(df[col]):
            continue
            
        # Probar conversión a numérico
        try:
            # Intentar convertir a numérico
            converted = pd.to_numeric(df[col].astype(str).str.replace(',', '.'), errors='coerce')
            
            # Contar valores convertidos exitosamente (no NaN)
            successful_conversions = converted.notna().sum()
            total_values = len(df)
            
            # Si más del 70% de los valores se pueden convertir, es potencialmente numérico
            if successful_conversions / total_values > 0.7 and successful_conversions > 0:
                potential_numeric.append(col)
                
        except Exception:
            continue
    
    return potential_numeric

def auto_convert_potential_numeric(df, columns_to_convert):
    """Convierte automáticamente columnas potencialmente numéricas"""
    new_df = df.copy()
    
    for col in columns_to_convert:
        try:
            # Intentar conversión reemplazando comas por puntos para decimales
            new_df[col] = pd.to_numeric(
                new_df[col].astype(str).str.replace(',', '.'), 
                errors='coerce'
            )
        except Exception as e:
            st.error(f"❌ Error convirtiendo '{col}': {str(e)}")
    
    return new_df

def show_data_converter(df):
    """Interfaz para conversión manual de tipos de datos"""
    st.subheader("🔧 Conversor de Tipos de Datos")
    
    st.info("""
    **Convierte columnas a diferentes tipos de datos para habilitar más análisis:**
    - **Numérico**: Para correlaciones, outliers, distribuciones
    - **Fecha/Hora**: Para análisis temporal
    - **Categoría**: Para optimizar memoria y análisis categóricos
    """)
    
    col1, col2, col3 = st.columns([2, 2, 1])
    
    with col1:
        selected_columns = st.multiselect(
            "Seleccionar columnas para convertir:",
            df.columns.tolist(),
            help="Selecciona las columnas que quieres convertir"
        )
    
    with col2:
        target_type = st.selectbox(
            "Convertir a:",
            ["Numérico", "Texto", "Fecha/Hora", "Categoría", "Booleano"],
            help="Elige el tipo de dato objetivo"
        )
    
    with col3:
        st.write("")  # Espacio vertical
        st.write("")
        if st.button("🔄 Convertir", type="primary"):
            if selected_columns:
                new_df = convert_columns(df, selected_columns, target_type)
                st.session_state.global_df = new_df
                st.success(f"✅ {len(selected_columns)} columnas convertidas a {target_type}")
                st.rerun()
            else:
                st.warning("Selecciona al menos una columna")
    
    # Mostrar resumen de tipos de datos actuales
    st.subheader("📊 Resumen de Tipos de Datos Actuales")
    
    type_summary = []
    for col in df.columns:
        type_summary.append({
            'Columna': col,
            'Tipo Actual': str(df[col].dtype),
            'No Nulos': df[col].notna().sum(),
            'Valores Únicos': df[col].nunique()
        })
    
    type_df = pd.DataFrame(type_summary)
    st.dataframe(type_df, use_container_width=True)
    
    # Detectar y sugerir conversiones automáticas
    potential_numeric = detect_potential_numeric_columns(df)
    if potential_numeric:
        st.subheader("💡 Sugerencias de Conversión Automática")
        st.write(f"**Columnas que podrían convertirse a numérico:** {', '.join(potential_numeric)}")
        
        if st.button("🎯 Aplicar conversiones sugeridas", key="auto_convert_suggested"):
            new_df = auto_convert_potential_numeric(df, potential_numeric)
            st.session_state.global_df = new_df
            st.success("¡Conversiones aplicadas! Ahora tienes columnas numéricas para análisis.")
            st.rerun()

def convert_columns(df, columns, target_type):
    """Convierte columnas al tipo de dato especificado"""
    new_df = df.copy()
    
    for col in columns:
        try:
            if target_type == "Numérico":
                new_df[col] = pd.to_numeric(new_df[col].astype(str).str.replace(',', '.'), errors='coerce')
            elif target_type == "Texto":
                new_df[col] = new_df[col].astype(str)
            elif target_type == "Fecha/Hora":
                new_df[col] = pd.to_datetime(new_df[col], errors='coerce')
            elif target_type == "Categoría":
                new_df[col] = new_df[col].astype('category')
            elif target_type == "Booleano":
                new_df[col] = new_df[col].astype(bool)
        except Exception as e:
            st.error(f"Error convirtiendo {col} a {target_type}: {str(e)}")
    
    return new_df

# =============================================================================
# FUNCIONES DE ANÁLISIS MEJORADAS CON DETECCIÓN DE COLUMNAS (MEJORADAS)
# =============================================================================

def show_correlation_analysis_improved(df, sample_size):
    """Análisis de correlaciones con detección mejorada - CORREGIDO TÍTULO DUPLICADO"""
    st.subheader("🔗 Análisis de Correlaciones")
    
    numeric_cols = df.select_dtypes(include=[np.number]).columns.tolist()
    
    if len(numeric_cols) < 2:
        st.warning("Se necesitan al menos 2 columnas numéricas para el análisis de correlación")
        st.info(f"**Columnas numéricas encontradas:** {len(numeric_cols)}")
        
        # Mostrar sugerencias de conversión
        potential_numeric = detect_potential_numeric_columns(df)
        if potential_numeric:
            st.success("💡 **Sugerencia:** Usa el '🔧 Conversor de Datos' para convertir columnas a numérico")
            st.write(f"**Columnas convertibles:** {', '.join(potential_numeric)}")
        else:
            st.info("💡 **Sugerencia:** Tu dataset no tiene columnas numéricas. Considera cargar datos con columnas numéricas.")
        
        return
    
    # Si hay columnas numéricas, continuar con el análisis normal
    show_correlation_analysis(df, sample_size)

def show_temporal_analysis_improved(df, sample_size):
    """Análisis temporal con detección mejorada - CORREGIDO ERROR COLUMNAS NO ÚNICAS"""
    st.subheader("📅 Análisis Temporal")
    
    # Asegurar que los nombres de columnas sean únicos
    df_temp = df.loc[:, ~df.columns.duplicated()].copy()
    
    # Detectar columnas de fecha
    date_columns = []
    for col in df_temp.columns:
        if pd.api.types.is_datetime64_any_dtype(df_temp[col]):
            date_columns.append(col)
        else:
            try:
                # Intentar detectar si es convertible a fecha
                sample_val = df_temp[col].dropna().iloc[0] if not df_temp[col].dropna().empty else ""
                if isinstance(sample_val, (int, float)) and abs(sample_val) > 1e10:
                    # Posible timestamp
                    date_columns.append(col)
                else:
                    pd.to_datetime(df_temp[col], errors='coerce')
                    date_columns.append(col)
            except:
                pass
    
    if not date_columns:
        st.warning("No se detectaron columnas de fecha en el dataset")
        st.info("💡 **Sugerencia:** Usa '🔧 Conversor de Datos' para convertir columnas a fecha/hora")
        return
    
    date_col = st.selectbox("Selecciona columna de fecha:", date_columns)
    
    numeric_cols = df_temp.select_dtypes(include=[np.number]).columns.tolist()
    
    if not numeric_cols:
        st.warning("No hay columnas numéricas para análisis temporal")
        
        # Mostrar sugerencias
        potential_numeric = detect_potential_numeric_columns(df_temp)
        if potential_numeric:
            st.success("💡 **Sugerencia:** Usa '🔧 Conversor de Datos' para convertir columnas a numérico")
            st.write(f"**Columnas convertibles:** {', '.join(potential_numeric)}")
        
        return
    
    analysis_col = st.selectbox("Selecciona columna para análisis:", numeric_cols)
    
    # Convertir a datetime si no lo está
    if not pd.api.types.is_datetime64_any_dtype(df_temp[date_col]):
        try:
            # Intentar detectar si es timestamp
            sample_val = df_temp[date_col].dropna().iloc[0] if not df_temp[date_col].dropna().empty else 0
            if isinstance(sample_val, (int, float)) and abs(sample_val) > 1e10:
                if abs(sample_val) > 1e12:  # nanosegundos
                    df_temp[date_col] = pd.to_datetime(df_temp[date_col] / 1000000, unit='ms', errors='coerce')
                else:
                    df_temp[date_col] = pd.to_datetime(df_temp[date_col], unit='ms', errors='coerce')
            else:
                df_temp[date_col] = pd.to_datetime(df_temp[date_col], errors='coerce')
        except Exception as e:
            st.error(f"Error convirtiendo fecha: {str(e)}")
            return
    
    temporal_df = df_temp[[date_col, analysis_col]].dropna()
    
    if len(temporal_df) > 0:
        try:
            fig_temporal = px.line(
                temporal_df.sort_values(date_col),
                x=date_col,
                y=analysis_col,
                title=f"Serie Temporal: {analysis_col}",
                markers=True
            )
            st.plotly_chart(fig_temporal, use_container_width=True)
            
            st.subheader("📈 Análisis de Tendencia")
            
            period = st.selectbox("Periodo de agrupación:", ["Día", "Semana", "Mes", "Año"])
            
            period_map = {"Día": "D", "Semana": "W", "Mes": "M", "Año": "Y"}
            try:
                grouped = temporal_df.set_index(date_col).resample(period_map[period])[analysis_col].mean()
                
                fig_trend = px.line(
                    x=grouped.index,
                    y=grouped.values,
                    title=f"Tendencia {period.lower()} de {analysis_col}",
                    labels={'x': 'Fecha', 'y': f'Media de {analysis_col}'}
                )
                st.plotly_chart(fig_trend, use_container_width=True)
            except Exception as e:
                st.error(f"No se pudo agrupar por periodo: {str(e)}")
        except Exception as e:
            st.error(f"No se pudo generar el análisis temporal: {str(e)}")

def show_outliers_analysis_improved(df, sample_size):
    """Análisis de outliers con detección mejorada"""
    st.subheader("🎯 Detección de Valores Atípicos (Outliers)")
    
    numeric_cols = df.select_dtypes(include=[np.number]).columns.tolist()
    
    if not numeric_cols:
        st.warning("No hay columnas numéricas para análisis de outliers")
        
        potential_numeric = detect_potential_numeric_columns(df)
        if potential_numeric:
            st.success("💡 **Sugerencia:** Usa '🔧 Conversor de Datos' para convertir columnas a numérico")
            st.write(f"**Columnas convertibles:** {', '.join(potential_numeric)}")
        else:
            st.info("💡 **Sugerencia:** Tu dataset no tiene columnas numéricas. Los outliers solo se pueden detectar en datos numéricos.")
        
        return
    
    selected_outlier_cols = st.multiselect(
        "Selecciona columnas para análisis de outliers:",
        numeric_cols,
        default=numeric_cols[:2] if len(numeric_cols) >= 2 else numeric_cols
    )
    
    if not selected_outlier_cols:
        st.warning("Selecciona al menos una columna")
        return
    
    detection_method = st.selectbox(
        "Método de detección:",
        ["IQR (Rango Intercuartílico)", "Z-Score", "Ambos"]
    )
    
    outliers_summary = []
    
    for col in selected_outlier_cols:
        with st.expander(f"🔍 Outliers en **{col}**", expanded=False):
            data = df[col].dropna()
            
            if len(data) == 0:
                st.warning("No hay datos válidos para analizar")
                continue
                
            iqr_outliers = pd.Series([])
            z_outliers = pd.Series([])
                
            if detection_method in ["IQR (Rango Intercuartílico)", "Ambos"]:
                try:
                    Q1 = data.quantile(0.25)
                    Q3 = data.quantile(0.75)
                    IQR = Q3 - Q1
                    lower_bound = Q1 - 1.5 * IQR
                    upper_bound = Q3 + 1.5 * IQR
                    
                    iqr_outliers = data[(data < lower_bound) | (data > upper_bound)]
                    st.write(f"**IQR - Outliers detectados:** {len(iqr_outliers)}")
                    st.write(f"Límite inferior: {lower_bound:.2f}, Límite superior: {upper_bound:.2f}")
                except Exception as e:
                    st.error(f"Error en método IQR: {str(e)}")
            
            if detection_method in ["Z-Score", "Ambos"]:
                try:
                    z_scores = np.abs(stats.zscore(data))
                    z_outliers = data[z_scores > 3]
                    st.write(f"**Z-Score - Outliers detectados:** {len(z_outliers)}")
                except Exception as e:
                    st.error(f"Error en método Z-Score: {str(e)}")
            
            try:
                fig_box = px.box(df, y=col, title=f"Boxplot de {col}")
                st.plotly_chart(fig_box, use_container_width=True)
            except Exception as e:
                st.error(f"No se pudo generar el boxplot: {str(e)}")
            
            if detection_method in ["IQR (Rango Intercuartílico)", "Ambos"] and len(iqr_outliers) > 0:
                try:
                    fig_hist = px.histogram(df, x=col, title=f"Distribución de {col} con Outliers")
                    st.plotly_chart(fig_hist, use_container_width=True)
                except Exception as e:
                    st.error(f"No se pudo generar el histograma: {str(e)}")
            
            outliers_summary.append({
                'Columna': col,
                'Total Outliers IQR': len(iqr_outliers) if detection_method in ["IQR (Rango Intercuartílico)", "Ambos"] else 0,
                'Total Outliers Z-Score': len(z_outliers) if detection_method in ["Z-Score", "Ambos"] else 0
            })
    
    if outliers_summary:
        st.subheader("📋 Resumen de Outliers por Columna")
        st.dataframe(pd.DataFrame(outliers_summary), use_container_width=True)

def show_distribution_analysis_improved(df, sample_size):
    """Análisis de distribución con detección mejorada"""
    st.subheader("📊 Análisis de Distribuciones")
    
    numeric_cols = df.select_dtypes(include=[np.number]).columns.tolist()
    
    if not numeric_cols:
        st.warning("No hay columnas numéricas para análisis de distribución")
        
        potential_numeric = detect_potential_numeric_columns(df)
        if potential_numeric:
            st.success("💡 **Sugerencia:** Usa '🔧 Conversor de Datos' para convertir columnas a numérico")
            st.write(f"**Columnas convertibles:** {', '.join(potential_numeric)}")
        else:
            st.info("💡 **Sugerencia:** Los análisis de distribución requieren datos numéricos.")
        
        return
    
    selected_dist_cols = st.multiselect(
        "Selecciona columnas para análisis de distribución:",
        numeric_cols,
        default=numeric_cols[:2] if len(numeric_cols) >= 2 else numeric_cols
    )
    
    if not selected_dist_cols:
        st.warning("Selecciona al menos una columna")
        return
    
    for col in selected_dist_cols:
        with st.expander(f"📈 Distribución de **{col}**", expanded=False):
            try:
                col1, col2 = st.columns(2)
                
                with col1:
                    if df[col].notna().sum() > 0:
                        try:
                            n_bins = min(50, max(5, df[col].nunique()))
                            fig_hist = px.histogram(
                                df, x=col, 
                                nbins=n_bins,
                                marginal="box",
                                title=f"Distribución de {col}"
                            )
                            st.plotly_chart(fig_hist, use_container_width=True)
                        except Exception as e:
                            st.error(f"No se pudo generar el histograma: {str(e)}")
                    else:
                        st.info("No hay datos para generar histograma")
                
                with col2:
                    data = df[col].dropna()
                    if len(data) > 1:
                        try:
                            fig_qq = go.Figure()
                            
                            theoretical_quantiles = stats.probplot(data, dist="norm")
                            
                            fig_qq.add_trace(go.Scatter(
                                x=theoretical_quantiles[0][0],
                                y=theoretical_quantiles[0][1],
                                mode='markers',
                                name='Datos'
                            ))
                            
                            fig_qq.add_trace(go.Scatter(
                                x=theoretical_quantiles[0][0],
                                y=theoretical_quantiles[1][0] * theoretical_quantiles[0][0] + theoretical_quantiles[1][1],
                                mode='lines',
                                name='Normal teórica'
                            ))
                            
                            fig_qq.update_layout(
                                title=f"QQ Plot - {col}",
                                xaxis_title="Cuantiles Teóricos",
                                yaxis_title="Cuantiles Observados"
                            )
                            st.plotly_chart(fig_qq, use_container_width=True)
                        except Exception as e:
                            st.error(f"No se pudo generar el QQ Plot: {str(e)}")
                    else:
                        st.info("Datos insuficientes para QQ Plot")
                
                data = df[col].dropna()
                if len(data) > 1:
                    st.write("**Prueba de Normalidad:**")
                    normality_col1, normality_col2, normality_col3 = st.columns(3)
                    
                    with normality_col1:
                        if len(data) <= 5000:
                            try:
                                shapiro_stat, shapiro_p = stats.shapiro(data)
                                st.metric("Shapiro-Wilk p-value", f"{shapiro_p:.4f}")
                            except:
                                st.write("Shapiro-Wilk: Error")
                        else:
                            st.write("Shapiro-Wilk: N > 5000")
                    
                    with normality_col2:
                        try:
                            ks_stat, ks_p = stats.kstest(data, 'norm', args=(data.mean(), data.std()))
                            st.metric("Kolmogorov-Smirnov p-value", f"{ks_p:.4f}")
                        except:
                            st.write("K-S: Error")
                    
                    with normality_col3:
                        try:
                            skewness = data.skew()
                            kurtosis = data.kurtosis()
                            st.metric("Asimetría", f"{skewness:.2f}")
                            st.metric("Curtosis", f"{kurtosis:.2f}")
                        except:
                            st.metric("Asimetría", "Error")
                            st.metric("Curtosis", "Error")
                            
            except Exception as e:
                st.error(f"Error analizando distribución de {col}: {str(e)}")

# =============================================================================
# FUNCIONES DE ANÁLISIS ORIGINALES (MEJORADAS)
# =============================================================================

def show_general_analysis(df, sample_size):
    """Análisis general completo del dataset"""
    st.subheader("📊 Análisis General del Dataset")
    
    with st.expander("👀 Vista Previa de Datos", expanded=True):
        st.dataframe(df.head(sample_size), use_container_width=True)
    
    col1, col2, col3, col4 = st.columns(4)
    
    with col1:
        st.metric("Total Filas", len(df))
        st.metric("Filas en Muestra", sample_size)
    
    with col2:
        st.metric("Total Columnas", len(df.columns))
        numeric_cols = df.select_dtypes(include=[np.number]).columns.tolist()
        st.metric("Columnas Numéricas", len(numeric_cols))
    
    with col3:
        categorical_cols = df.select_dtypes(include=['object']).columns.tolist()
        st.metric("Columnas Categóricas", len(categorical_cols))
        st.metric("Memoria Usada", f"{df.memory_usage(deep=True).sum() / 1024 / 1024:.2f} MB")
    
    with col4:
        duplicate_rows = df.duplicated().sum()
        st.metric("Filas Duplicadas", duplicate_rows)
        missing_values = df.isnull().sum().sum()
        st.metric("Valores Faltantes", missing_values)
    
    st.subheader("📈 Distribución de Tipos de Datos")
    
    dtype_counts = df.dtypes.value_counts()
    
    if len(dtype_counts) > 0:
        try:
            fig_dtype = px.pie(
                values=dtype_counts.values,
                names=[str(dtype) for dtype in dtype_counts.index],
                title="Distribución de Tipos de Datos"
            )
            st.plotly_chart(fig_dtype, use_container_width=True)
        except Exception as e:
            st.error(f"No se pudo generar el gráfico de tipos: {str(e)}")
    
    if df.isnull().sum().sum() > 0:
        st.subheader("⚠️ Análisis de Valores Faltantes")
        
        missing_data = df.isnull().sum()
        missing_data = missing_data[missing_data > 0]
        
        if len(missing_data) > 0:
            try:
                fig_missing = px.bar(
                    x=missing_data.index,
                    y=missing_data.values,
                    title="Valores Faltantes por Columna",
                    labels={'x': 'Columna', 'y': 'Valores Faltantes'}
                )
                st.plotly_chart(fig_missing, use_container_width=True)
            except Exception as e:
                st.error(f"No se pudo generar el gráfico de valores faltantes: {str(e)}")
    
    with st.expander("📋 Resumen Estadístico Completo", expanded=False):
        numeric_cols = df.select_dtypes(include=[np.number]).columns.tolist()
        if len(numeric_cols) > 0:
            st.dataframe(df[numeric_cols].describe(), use_container_width=True)
        else:
            st.info("No hay columnas numéricas para mostrar estadísticas")

def show_column_analysis_improved(df, selected_columns, sample_size):
    """Análisis detallado por columnas - MEJORADO PARA FECHAS"""
    st.subheader("🎯 Análisis por Columnas")
    
    if not selected_columns:
        st.warning("Selecciona al menos una columna para analizar")
        return
    
    for col in selected_columns:
        with st.expander(f"📊 Análisis de: **{col}**", expanded=False):
            try:
                col1, col2 = st.columns(2)
                
                with col1:
                    st.write(f"**Tipo de dato:** {df[col].dtype}")
                    st.write(f"**Valores únicos:** {df[col].nunique()}")
                    st.write(f"**Valores faltantes:** {df[col].isnull().sum()}")
                    st.write(f"**Porcentaje faltante:** {df[col].isnull().mean() * 100:.2f}%")
                    
                    if df[col].dtype == 'object':
                        empty_count = (df[col].astype(str) == '').sum()
                    else:
                        empty_count = 0
                    st.write(f"**Valores vacíos:** {empty_count}")
                    
                    # MEJORA: Manejar fechas de manera especial
                    if pd.api.types.is_datetime64_any_dtype(df[col]):
                        st.write("**Frecuencia de valores (fechas):**")
                        # Formatear fechas para mostrar
                        date_counts = df[col].dt.strftime('%Y-%m-%d').value_counts()
                        st.dataframe(date_counts, use_container_width=True)
                    elif df[col].nunique() <= 20 and df[col].nunique() > 0:
                        st.write("**Frecuencia de valores:**")
                        value_counts = df[col].value_counts()
                        st.dataframe(value_counts, use_container_width=True)
                    elif df[col].nunique() == 0:
                        st.warning("⚠️ Columna vacía o todos los valores son nulos")
                    else:
                        st.write(f"**Demasiados valores únicos ({df[col].nunique()})**")
                        st.write("**Top 10 valores:**")
                        top_values = df[col].value_counts().head(10)
                        st.dataframe(top_values, use_container_width=True)
                
                with col2:
                    if pd.api.types.is_numeric_dtype(df[col]):
                        try:
                            if df[col].notna().sum() > 0:
                                n_bins = min(50, max(5, df[col].nunique()))
                                fig_hist = px.histogram(
                                    df, x=col, 
                                    title=f"Distribución de {col}",
                                    nbins=n_bins
                                )
                                st.plotly_chart(fig_hist, use_container_width=True)
                            else:
                                st.info("No hay datos numéricos para graficar")
                        except Exception as e:
                            st.error(f"No se pudo generar el histograma: {str(e)}")
                        
                    elif pd.api.types.is_datetime64_any_dtype(df[col]):
                        try:
                            if df[col].notna().sum() > 0:
                                date_data = df[col].dropna()
                                fig_date = px.histogram(
                                    x=date_data,
                                    title=f"Distribución de {col}",
                                    labels={'x': col}
                                )
                                st.plotly_chart(fig_date, use_container_width=True)
                            else:
                                st.info("No hay fechas válidas para graficar")
                        except Exception as e:
                            st.error(f"No se pudo generar el gráfico de fechas: {str(e)}")
                    else:
                        try:
                            if df[col].notna().sum() > 0:
                                top_values = df[col].value_counts().head(10)
                                if len(top_values) > 0:
                                    fig_bar = px.bar(
                                        x=top_values.index,
                                        y=top_values.values,
                                        title=f"Top 10 Valores en {col}",
                                        labels={'x': col, 'y': 'Frecuencia'}
                                    )
                                    st.plotly_chart(fig_bar, use_container_width=True)
                                else:
                                    st.info("No hay datos categóricos para graficar")
                            else:
                                st.info("Columna vacía")
                        except Exception as e:
                            st.error(f"No se pudo generar el gráfico de barras: {str(e)}")
                
                # MEJORA: Mostrar estadísticas para fechas también
                if pd.api.types.is_numeric_dtype(df[col]) and df[col].notna().sum() > 0:
                    st.write("**Estadísticas Detalladas:**")
                    stats_col1, stats_col2, stats_col3, stats_col4 = st.columns(4)
                    
                    with stats_col1:
                        st.metric("Media", f"{df[col].mean():.2f}")
                        st.metric("Mediana", f"{df[col].median():.2f}")
                    
                    with stats_col2:
                        if df[col].notna().sum() > 1:
                            st.metric("Desv. Estándar", f"{df[col].std():.2f}")
                            st.metric("Varianza", f"{df[col].var():.2f}")
                        else:
                            st.metric("Desv. Estándar", "N/A")
                            st.metric("Varianza", "N/A")
                    
                    with stats_col3:
                        st.metric("Mínimo", f"{df[col].min():.2f}")
                        st.metric("Máximo", f"{df[col].max():.2f}")
                    
                    with stats_col4:
                        if df[col].notna().sum() > 2:
                            st.metric("Asimetría", f"{df[col].skew():.2f}")
                            st.metric("Curtosis", f"{df[col].kurtosis():.2f}")
                        else:
                            st.metric("Asimetría", "N/A")
                            st.metric("Curtosis", "N/A")
                
                elif pd.api.types.is_datetime64_any_dtype(df[col]) and df[col].notna().sum() > 0:
                    st.write("**Estadísticas de Fechas:**")
                    date_stats_col1, date_stats_col2 = st.columns(2)
                    
                    with date_stats_col1:
                        st.metric("Fecha Mínima", df[col].min().strftime('%Y-%m-%d'))
                        st.metric("Fecha Máxima", df[col].max().strftime('%Y-%m-%d'))
                    
                    with date_stats_col2:
                        st.metric("Rango (días)", f"{(df[col].max() - df[col].min()).days}")
                        st.metric("Valores Únicos", df[col].nunique())
                            
            except Exception as e:
                st.error(f"Error analizando columna {col}: {str(e)}")

def show_correlation_analysis(df, sample_size):
    """Análisis de correlaciones entre variables - CORREGIDO TÍTULO DUPLICADO"""
    # st.subheader("🔗 Análisis de Correlaciones")  # <-- ESTE ERA EL DUPLICADO, LO ELIMINÉ
    
    numeric_df = df.select_dtypes(include=[np.number])
    
    if len(numeric_df.columns) < 2:
        st.warning("Se necesitan al menos 2 columnas numéricas para el análisis de correlación")
        st.info(f"Columnas numéricas encontradas: {len(numeric_df.columns)}")
        return
    
    corr_method = st.selectbox(
        "Método de correlación:",
        ["Pearson", "Spearman", "Kendall"]
    )
    
    method_map = {"Pearson": "pearson", "Spearman": "spearman", "Kendall": "kendall"}
    
    try:
        correlation_matrix = numeric_df.corr(method=method_map[corr_method])
        
        fig_corr = px.imshow(
            correlation_matrix,
            title=f"Mapa de Calor de Correlaciones ({corr_method})",
            aspect="auto",
            color_continuous_scale="RdBu_r"
        )
        st.plotly_chart(fig_corr, use_container_width=True)
        
        st.subheader("💪 Correlaciones Más Fuertes")
        
        corr_pairs = []
        for i in range(len(correlation_matrix.columns)):
            for j in range(i+1, len(correlation_matrix.columns)):
                corr_pairs.append({
                    'Variable 1': correlation_matrix.columns[i],
                    'Variable 2': correlation_matrix.columns[j],
                    'Correlación': correlation_matrix.iloc[i, j]
                })
        
        corr_df = pd.DataFrame(corr_pairs)
        corr_df['Abs_Correlation'] = corr_df['Correlación'].abs()
        corr_df = corr_df.sort_values('Abs_Correlation', ascending=False)
        
        top_correlations = corr_df.head(10)
        st.dataframe(top_correlations, use_container_width=True)
        
        st.subheader("📈 Gráficos de Dispersión - Pares con Alta Correlación")
        
        if len(top_correlations) > 0:
            for _, pair in top_correlations.head(3).iterrows():
                try:
                    fig_scatter = px.scatter(
                        df,
                        x=pair['Variable 1'],
                        y=pair['Variable 2'],
                        title=f"{pair['Variable 1']} vs {pair['Variable 2']} (r={pair['Correlación']:.3f})",
                        trendline="ols"
                    )
                    st.plotly_chart(fig_scatter, use_container_width=True)
                except Exception as e:
                    st.error(f"No se pudo generar el gráfico de dispersión: {str(e)}")
                    
    except Exception as e:
        st.error(f"Error en análisis de correlaciones: {str(e)}")

# =============================================================================
# ANÁLISIS DE CALIDAD MEJORADO (MANTENIDO)
# =============================================================================

def calculate_quality_metrics(df):
    """Calcula métricas avanzadas de calidad"""
    try:
        total_cells = df.size
        null_cells = df.isnull().sum().sum()
        empty_cells = (df.astype(str) == '').sum().sum()
        duplicate_rows = df.duplicated().sum()
        
        quality_score = max(0, 100 - (
            (null_cells + empty_cells) / total_cells * 70 +
            (duplicate_rows / len(df)) * 30
        )) if total_cells > 0 else 0
        
        critical_issues = 0
        medium_issues = 0
        
        for col in df.columns:
            null_pct = df[col].isna().mean()
            unique_ratio = df[col].nunique() / len(df) if len(df) > 0 else 0
            
            if null_pct > 0.5 or unique_ratio == 0:
                critical_issues += 1
            elif null_pct > 0.1 or unique_ratio < 0.01:
                medium_issues += 1
        
        return {
            'quality_score': quality_score,
            'critical_issues': critical_issues,
            'medium_issues': medium_issues,
            'affected_rows': duplicate_rows + (df.isnull().any(axis=1)).sum(),
            'affected_columns': (df.isnull().sum() > 0).sum(),
            'memory_usage': df.memory_usage(deep=True).sum() / 1024 / 1024
        }
    except Exception as e:
        st.error(f"Error calculando métricas: {str(e)}")
        return {
            'quality_score': 0,
            'critical_issues': 0,
            'medium_issues': 0,
            'affected_rows': 0,
            'affected_columns': 0,
            'memory_usage': 0
        }

def analyze_data_quality(df):
    """Analiza la calidad de datos por columna"""
    quality_data = []
    
    for col in df.columns:
        try:
            col_type = str(df[col].dtype)
            total_values = len(df)
            non_null_count = df[col].notna().sum()
            null_count = df[col].isna().sum()
            
            if df[col].dtype == 'object':
                empty_count = (df[col].astype(str) == '').sum()
            else:
                empty_count = 0
            
            unique_count = df[col].nunique()
            duplicate_count = df[col].duplicated().sum()
            is_constant = unique_count <= 1
            
            col_data = {
                'Columna': col,
                'Tipo_Dato': col_type,
                'Total_Valores': total_values,
                'No_Nulos': non_null_count,
                'Nulos': null_count,
                'Porcentaje_Nulos': (null_count / total_values * 100) if total_values > 0 else 0,
                'Vacios': empty_count,
                'Valores_Únicos': unique_count,
                'Duplicados_Columna': duplicate_count,
                'Es_Constante': is_constant
            }
            
            problemas = []
            severidad = 0
            
            if col_data['Nulos'] > 0:
                problemas.append(f"{col_data['Nulos']} nulos")
                severidad += min(3, col_data['Nulos'] / total_values * 10)
            
            if col_data['Vacios'] > 0:
                problemas.append(f"{col_data['Vacios']} vacíos")
                severidad += min(2, col_data['Vacios'] / total_values * 5)
            
            if col_data['Es_Constante']:
                problemas.append("constante")
                severidad += 5
            
            if col_data['Duplicados_Columna'] > total_values * 0.5:
                problemas.append("muchos duplicados")
                severidad += 3
            
            col_data['Problemas_Detectados'] = ", ".join(problemas) if problemas else "✅ OK"
            col_data['Tiene_Problemas'] = len(problemas) > 0
            col_data['Severidad'] = severidad
            
            quality_data.append(col_data)
        except Exception as e:
            st.error(f"Error analizando columna {col}: {str(e)}")
            continue
    
    return sorted(quality_data, key=lambda x: x['Severidad'], reverse=True)

def display_quality_summary(quality_data):
    """Muestra resumen visual de problemas"""
    try:
        if not quality_data:
            st.info("No hay datos de calidad para mostrar")
            return
        
        quality_df = pd.DataFrame(quality_data)
        
        col1, col2, col3, col4 = st.columns(4)
        
        with col1:
            total_problemas = quality_df['Tiene_Problemas'].sum()
            st.metric("Columnas Problemáticas", int(total_problemas))
        
        with col2:
            total_nulos = quality_df['Nulos'].sum()
            st.metric("Total Valores Nulos", int(total_nulos))
        
        with col3:
            total_vacios = quality_df['Vacios'].sum()
            st.metric("Total Valores Vacíos", int(total_vacios))
        
        with col4:
            constantes = quality_df['Es_Constante'].sum()
            st.metric("Columnas Constantes", int(constantes))
        
        problem_df = quality_df[quality_df['Tiene_Problemas']]
        if not problem_df.empty:
            try:
                fig = px.bar(
                    problem_df,
                    x='Columna',
                    y='Severidad',
                    color='Severidad',
                    title="Severidad de Problemas por Columna",
                    color_continuous_scale='reds'
                )
                fig.update_layout(xaxis_tickangle=-45)
                st.plotly_chart(fig, use_container_width=True)
            except Exception as e:
                st.warning(f"No se pudo generar el gráfico de severidad: {str(e)}")
        
        st.subheader("📋 Detalle por Columna")
        display_cols = ['Columna', 'Tipo_Dato', 'Nulos', 'Vacios', 'Valores_Únicos', 'Problemas_Detectados']
        st.dataframe(quality_df[display_cols], use_container_width=True)
        
    except Exception as e:
        st.error(f"Error mostrando resumen de calidad: {str(e)}")

def render_column_editor(df, row):
    """Renderiza el editor interactivo para cada columna"""
    try:
        col = row['Columna']
        
        st.write(f"**Tipo de dato:** {row['Tipo_Dato']}")
        st.write(f"**Valores únicos:** {row['Valores_Únicos']}")
        
        if row['Nulos'] > 0:
            st.write("---")
            st.write(f"**🔄 Valores Nulos:** {row['Nulos']} ({row['Porcentaje_Nulos']:.1f}%)")
            
            n_col1, n_col2, n_col3 = st.columns(3)
            
            with n_col1:
                if st.button(f"🗑️ Eliminar nulos", key=f"del_null_{col}"):
                    new_df = df.dropna(subset=[col])
                    st.session_state.global_df = new_df
                    if 'quality_changes' in st.session_state:
                        st.session_state.quality_changes.append(f"Eliminados nulos en {col}")
                    st.rerun()
            
            with n_col2:
                if pd.api.types.is_numeric_dtype(df[col]):
                    if st.button(f"📊 Imputar media", key=f"imp_mean_{col}"):
                        media = df[col].mean()
                        new_df = df.copy()
                        new_df[col].fillna(media, inplace=True)
                        st.session_state.global_df = new_df
                        if 'quality_changes' in st.session_state:
                            st.session_state.quality_changes.append(f"Imputada media en {col}: {media:.2f}")
                        st.rerun()
                else:
                    if st.button(f"📝 Imputar moda", key=f"imp_mode_{col}"):
                        moda = df[col].mode()[0] if not df[col].mode().empty else "DESCONOCIDO"
                        new_df = df.copy()
                        new_df[col].fillna(moda, inplace=True)
                        st.session_state.global_df = new_df
                        if 'quality_changes' in st.session_state:
                            st.session_state.quality_changes.append(f"Imputada moda en {col}: {moda}")
                        st.rerun()
            
            with n_col3:
                valor_personalizado = st.text_input(
                    "Valor personalizado:",
                    value="0" if pd.api.types.is_numeric_dtype(df[col]) else "VALOR_FALTANTE",
                    key=f"custom_val_{col}"
                )
                if st.button(f"✅ Aplicar", key=f"apply_custom_{col}"):
                    try:
                        new_df = df.copy()
                        if pd.api.types.is_numeric_dtype(df[col]):
                            valor = float(valor_personalizado)
                        else:
                            valor = str(valor_personalizado)
                        
                        new_df[col].fillna(valor, inplace=True)
                        st.session_state.global_df = new_df
                        if 'quality_changes' in st.session_state:
                            st.session_state.quality_changes.append(f"Imputado valor personalizado en {col}")
                        st.rerun()
                    except ValueError:
                        st.error("Valor incompatible con el tipo de dato")
        
        if row['Vacios'] > 0:
            st.write("---")
            st.write(f"**📝 Valores Vacíos:** {row['Vacios']}")
            
            v_col1, v_col2 = st.columns(2)
            
            with v_col1:
                if st.button(f"🗑️ Eliminar vacíos", key=f"del_empty_{col}"):
                    new_df = df[df[col] != '']
                    st.session_state.global_df = new_df
                    if 'quality_changes' in st.session_state:
                        st.session_state.quality_changes.append(f"Eliminados vacíos en {col}")
                    st.rerun()
            
            with v_col2:
                valor_reemplazo = st.text_input(
                    "Reemplazar con:",
                    value="NO_ESPECIFICADO",
                    key=f"replace_empty_{col}"
                )
                if st.button(f"🔄 Reemplazar", key=f"rep_empty_{col}"):
                    new_df = df.copy()
                    new_df[col] = new_df[col].replace('', valor_reemplazo)
                    st.session_state.global_df = new_df
                    if 'quality_changes' in st.session_state:
                        st.session_state.quality_changes.append(f"Reemplazados vacíos en {col}")
                    st.rerun()
        
        if row['Es_Constante']:
            st.write("---")
            st.write("**⚠️ Columna Constante**")
            
            if st.button(f"❌ Eliminar columna", key=f"del_col_{col}", type="primary"):
                new_df = df.drop(columns=[col])
                st.session_state.global_df = new_df
                if 'quality_changes' in st.session_state:
                    st.session_state.quality_changes.append(f"Eliminada columna constante: {col}")
                st.rerun()
        
        st.write("---")
        st.write("**🔧 Conversión de Tipo de Dato**")
        
        tipo_actual = df[col].dtype
        nuevo_tipo = st.selectbox(
            "Convertir a:",
            ["Mantener actual", "Numérico", "Texto", "Fecha/Hora", "Categoría"],
            key=f"type_conv_{col}"
        )
        
        if st.button(f"🔄 Convertir tipo", key=f"convert_{col}"):
            try:
                new_df = df.copy()
                if nuevo_tipo == "Numérico":
                    new_df[col] = pd.to_numeric(new_df[col], errors='coerce')
                elif nuevo_tipo == "Texto":
                    new_df[col] = new_df[col].astype(str)
                elif nuevo_tipo == "Fecha/Hora":
                    new_df[col] = pd.to_datetime(new_df[col], errors='coerce')
                elif nuevo_tipo == "Categoría":
                    new_df[col] = new_df[col].astype('category')
                
                st.session_state.global_df = new_df
                if 'quality_changes' in st.session_state:
                    st.session_state.quality_changes.append(f"Convertido {col} a {nuevo_tipo}")
                st.rerun()
            except Exception as e:
                st.error(f"Error en conversión: {str(e)}")
                
    except Exception as e:
        st.error(f"Error en editor de columna: {str(e)}")

def basic_auto_clean(df):
    """Limpieza automática básica"""
    try:
        new_df = df.copy()
        
        constant_cols = [col for col in new_df.columns if new_df[col].nunique() <= 1]
        if constant_cols:
            new_df = new_df.drop(columns=constant_cols)
        
        filas_antes = len(new_df)
        new_df = new_df.drop_duplicates()
        filas_despues = len(new_df)
        
        high_null_cols = [col for col in new_df.columns if new_df[col].isna().mean() > 0.95]
        if high_null_cols:
            new_df = new_df.drop(columns=high_null_cols)
        
        return new_df
    except Exception as e:
        st.error(f"Error en limpieza básica: {str(e)}")
        return df

def advanced_auto_clean(df, quality_data):
    """Limpieza automática avanzada basada en reglas"""
    try:
        new_df = df.copy()
        changes = []
        
        for row in quality_data:
            col = row['Columna']
            
            if row['Nulos'] > 0 and pd.api.types.is_numeric_dtype(new_df[col]):
                if row['Porcentaje_Nulos'] < 30:
                    media = new_df[col].mean()
                    new_df[col].fillna(media, inplace=True)
                    changes.append(f"Imputados nulos en {col} con media")
            
            elif row['Nulos'] > 0 and not pd.api.types.is_numeric_dtype(new_df[col]):
                if row['Porcentaje_Nulos'] < 30:
                    moda = new_df[col].mode()[0] if not new_df[col].mode().empty else "DESCONOCIDO"
                    new_df[col].fillna(moda, inplace=True)
                    changes.append(f"Imputados nulos en {col} con moda")
            
            if row['Vacios'] > 0:
                new_df[col] = new_df[col].replace('', 'NO_ESPECIFICADO')
                changes.append(f"Reemplazados vacíos en {col}")
        
        return new_df
    except Exception as e:
        st.error(f"Error en limpieza avanzada: {str(e)}")
        return df

def normalize_text_columns(df):
    """Normaliza columnas de texto"""
    try:
        new_df = df.copy()
        for col in new_df.select_dtypes(include=['object']).columns:
            new_df[col] = new_df[col].astype(str).str.strip()
            new_df[col] = new_df[col].str.upper()
            new_df[col] = new_df[col].str.replace(r'\s+', ' ', regex=True)
        
        return new_df
    except Exception as e:
        st.error(f"Error normalizando textos: {str(e)}")
        return df

def generate_quality_report(quality_data):
    """Genera reporte CSV de calidad"""
    try:
        report_df = pd.DataFrame(quality_data)
        return report_df.to_csv(index=False, encoding='utf-8')
    except Exception as e:
        st.error(f"Error generando reporte: {str(e)}")
        return ""

def show_quality_analysis_improved(df):
    """Análisis completo de calidad de datos con acciones correctivas"""
    try:
        st.subheader("⚠️ Análisis de Calidad de Datos")
        
        if 'quality_changes' not in st.session_state:
            st.session_state.quality_changes = []
        if 'backup_df' not in st.session_state:
            st.session_state.backup_df = df.copy()
        
        st.subheader("📊 Dashboard de Calidad")
        
        quality_metrics = calculate_quality_metrics(df)
        
        col1, col2, col3, col4 = st.columns(4)
        
        with col1:
            st.metric("Puntuación Calidad", f"{quality_metrics['quality_score']:.1f}%")
            st.progress(quality_metrics['quality_score'] / 100)
        
        with col2:
            st.metric("Problemas Críticos", quality_metrics['critical_issues'])
            st.metric("Problemas Medios", quality_metrics['medium_issues'])
        
        with col3:
            st.metric("Filas Afectadas", quality_metrics['affected_rows'])
            st.metric("Columnas Afectadas", quality_metrics['affected_columns'])
        
        with col4:
            st.metric("Memoria Actual", f"{quality_metrics['memory_usage']:.2f} MB")
            if st.button("💾 Crear Backup"):
                st.session_state.backup_df = df.copy()
                st.success("Backup creado correctamente")
        
        if quality_metrics['critical_issues'] > 0:
            st.error(f"🚨 ALERTA: {quality_metrics['critical_issues']} problemas críticos detectados")
        if quality_metrics['medium_issues'] > 0:
            st.warning(f"⚠️ AVISO: {quality_metrics['medium_issues']} problemas medios detectados")
        
        st.subheader("🛠️ Panel de Limpieza de Datos")
        
        quality_data = analyze_data_quality(df)
        
        with st.expander("📋 Resumen de Problemas Detectados", expanded=True):
            display_quality_summary(quality_data)
        
        st.subheader("🤖 Acciones Automáticas Inteligentes")
        
        auto_col1, auto_col2, auto_col3 = st.columns(3)
        
        with auto_col1:
            if st.button("🔧 Limpieza Automática Básica", help="Elimina columnas constantes y duplicados exactos"):
                new_df = basic_auto_clean(df)
                st.session_state.global_df = new_df
                st.session_state.quality_changes.append("Limpieza automática básica aplicada")
                st.rerun()
        
        with auto_col2:
            if st.button("🎯 Limpieza Avanzada", help="Limpieza inteligente basada en reglas"):
                new_df = advanced_auto_clean(df, quality_data)
                st.session_state.global_df = new_df
                st.session_state.quality_changes.append("Limpieza avanzada aplicada")
                st.rerun()
        
        with auto_col3:
            if st.button("🔄 Restaurar Backup", type="secondary"):
                if st.session_state.backup_df is not None:
                    st.session_state.global_df = st.session_state.backup_df.copy()
                    st.session_state.quality_changes.append("Backup restaurado")
                    st.rerun()
                else:
                    st.error("No hay backup disponible")
        
        st.subheader("🎛️ Editor Interactivo por Columna")
        
        for row in quality_data:
            if row['Tiene_Problemas']:
                with st.expander(f"🔧 **{row['Columna']}** - {row['Problemas_Detectados']}", expanded=False):
                    render_column_editor(df, row)
        
        st.subheader("⚙️ Herramientas Avanzadas")
        
        adv_col1, adv_col2 = st.columns(2)
        
        with adv_col1:
            st.write("**Gestión de Valores Faltantes Masivos**")
            threshold_nulos = st.slider("Umbral para eliminar columnas (% nulos):", 0, 100, 80)
            if st.button("🗑️ Eliminar columnas con muchos nulos"):
                columnas_eliminar = []
                for col in df.columns:
                    pct_nulos = df[col].isna().mean() * 100
                    if pct_nulos > threshold_nulos:
                        columnas_eliminar.append(col)
                
                if columnas_eliminar:
                    new_df = df.drop(columns=columnas_eliminar)
                    st.session_state.global_df = new_df
                    st.session_state.quality_changes.append(f"Eliminadas {len(columnas_eliminar)} columnas con >{threshold_nulos}% nulos")
                    st.rerun()
                else:
                    st.info("No hay columnas que cumplan el criterio")
        
        with adv_col2:
            st.write("**Normalización de Texto**")
            if st.button("🔠 Estandarizar textos"):
                new_df = normalize_text_columns(df)
                st.session_state.global_df = new_df
                st.session_state.quality_changes.append("Textos estandarizados")
                st.rerun()
        
        if st.session_state.quality_changes:
            with st.expander("📝 Historial de Cambios", expanded=False):
                for i, change in enumerate(st.session_state.quality_changes[-10:], 1):
                    st.write(f"{i}. {change}")
                
                if st.button("🧹 Limpiar historial"):
                    st.session_state.quality_changes = []
                    st.rerun()
        
        st.subheader("📤 Exportar Resultados")
        
        exp_col1, exp_col2, exp_col3 = st.columns(3)
        
        with exp_col1:
            if st.button("💾 Guardar DataFrame Limpio"):
                st.session_state.global_df = df
                st.success("DataFrame actualizado en sesión")
        
        with exp_col2:
            csv = generate_quality_report(quality_data)
            st.download_button(
                label="📄 Descargar Reporte Calidad",
                data=csv,
                file_name=f"quality_report_{datetime.now().strftime('%Y%m%d_%H%M')}.csv",
                mime="text/csv"
            )
        
        with exp_col3:
            if st.button("🔄 Actualizar Análisis"):
                st.rerun()
                
    except Exception as e:
        st.error(f"Error crítico en análisis de calidad: {str(e)}")
        st.info("🔧 Algunos módulos pueden estar en desarrollo")

def get_image_download_link(fig, filename):
    """Genera un link de descarga para gráficos Plotly"""
    try:
        buffer = io.StringIO()
        fig.write_html(buffer, include_plotlyjs='cdn')
        html_bytes = buffer.getvalue().encode()
        b64 = base64.b64encode(html_bytes).decode()
        href = f'<a href="data:text/html;base64,{b64}" download="{filename}.html">Descargar Gráfico</a>'
        return href
    except Exception as e:
        return f"Error generando enlace: {str(e)}"

if __name__ == "__main__":
    show()