File size: 13,140 Bytes
68e9069
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import streamlit as st
import json
import hashlib
import os

class ConfigurationPanel:
    def __init__(self):
        self.password_file = "admin_config.txt"
        self.config_file = "app_config.json"
        
    def verify_admin_password(self, password_input):
        """Verificar contraseña de administrador de forma segura"""
        try:
            # Crear archivo de configuración si no existe
            if not os.path.exists(self.password_file):
                # Contraseña por defecto: "admin123" (debes cambiarla)
                default_password_hash = hashlib.sha256("admin123".encode()).hexdigest()
                with open(self.password_file, 'w') as f:
                    f.write(default_password_hash)
                return False
            
            # Leer hash almacenado
            with open(self.password_file, 'r') as f:
                stored_hash = f.read().strip()
            
            # Verificar contraseña
            input_hash = hashlib.sha256(password_input.encode()).hexdigest()
            return input_hash == stored_hash
            
        except Exception as e:
            st.error(f"Error verificando contraseña: {e}")
            return False
    
    def show_password_modal(self, action_type):
        """Mostrar modal para verificar contraseña para diferentes acciones"""
        
        # Inicializar estados por tipo de acción
        modal_key = f'show_password_{action_type}'
        attempts_key = f'password_attempts_{action_type}'
        
        if modal_key not in st.session_state:
            st.session_state[modal_key] = False
        if attempts_key not in st.session_state:
            st.session_state[attempts_key] = 0
        
        # Si la sección está visible
        if st.session_state[modal_key]:
            st.markdown("---")
            st.warning("🔒 **ACCIÓN ADMINISTRATIVA - Se requiere contraseña**")
            
            max_attempts = 3
            remaining = max_attempts - st.session_state[attempts_key]
            
            # Verificar si se alcanzó el límite de intentos
            if st.session_state[attempts_key] >= max_attempts:
                st.error("🚫 **Demasiados intentos fallidos. Sección bloqueada.**")
                if st.button("❌ Cerrar", key=f"close_blocked_{action_type}"):
                    st.session_state[modal_key] = False
                    st.session_state[attempts_key] = 0
                    st.rerun()
                return False
            
            st.write(f"**Intentos restantes:** {remaining}")
            
            # Input de contraseña
            password = st.text_input(
                "**Contraseña de administrador:**",
                type="password",
                help="Ingresa la contraseña para ejecutar esta acción",
                key=f"admin_password_{action_type}"
            )
            
            col1, col2 = st.columns(2)
            
            with col1:
                if st.button("✅ Verificar", type="primary", key=f"verify_{action_type}"):
                    if password:
                        if self.verify_admin_password(password):
                            # ✅ CONTRASEÑA CORRECTA
                            st.session_state[modal_key] = False
                            st.session_state[attempts_key] = 0
                            return True  # Acción autorizada
                        else:
                            # ❌ CONTRASEÑA INCORRECTA
                            st.session_state[attempts_key] += 1
                            remaining_after = max_attempts - st.session_state[attempts_key]
                            
                            if remaining_after > 0:
                                st.error(f"❌ **Contraseña incorrecta.** Te quedan {remaining_after} intentos.")
                            else:
                                st.error("❌ **Contraseña incorrecta.** No te quedan más intentos.")
                            st.rerun()
                    else:
                        st.warning("⚠️ Por favor ingresa una contraseña")
            
            with col2:
                if st.button("❌ Cancelar", key=f"cancel_{action_type}"):
                    st.session_state[modal_key] = False
                    st.session_state[attempts_key] = 0
                    st.rerun()
        
        return False
    
    def save_configuration(self):
        """Guardar configuración actual"""
        try:
            config = {
                "theme": {
                    "primary_color": st.session_state.get("primary_color", "#FF4B4B"),
                    "secondary_color": st.session_state.get("secondary_color", "#00D4AA"),
                    "dark_mode": st.session_state.get("dark_mode", True),
                    "layout_type": st.session_state.get("layout_type", "Wide"),
                    "sidebar_width": st.session_state.get("sidebar_width", 280)
                },
                "modules": {
                    "max_file_size": st.session_state.get("max_file_size", 100),
                    "max_rows": st.session_state.get("max_rows", 50000),
                    "api_framework": st.session_state.get("api_framework", "FastAPI"),
                    "auto_docs": st.session_state.get("auto_docs", True),
                    "auto_validation": st.session_state.get("auto_validation", True),
                    "db_engine": st.session_state.get("db_engine", "SQLite"),
                    "auto_backup": st.session_state.get("auto_backup", True),
                    "auto_indexes": st.session_state.get("auto_indexes", True)
                }
            }
            
            with open(self.config_file, 'w') as f:
                json.dump(config, f, indent=2)
            
            return True
        except Exception as e:
            st.error(f"Error guardando configuración: {e}")
            return False

def show():
    config_panel = ConfigurationPanel()
    
    st.header("🎛️ Panel de Configuración Avanzado")
    
    col1, col2 = st.columns([2, 1])
    
    with col1:
        # Configuración de temas
        st.subheader("🎨 Personalización de Tema")
        
        theme_tab1, theme_tab2, theme_tab3 = st.tabs(["Colores", "Layout", "Avanzado"])
        
        with theme_tab1:
            primary_color = st.color_picker("Color primario", "#FF4B4B", key="primary_color")
            secondary_color = st.color_picker("Color secundario", "#00D4AA", key="secondary_color")
            dark_mode = st.toggle("Modo oscuro", value=True, key="dark_mode")
            
        with theme_tab2:
            layout_type = st.selectbox("Tipo de layout", ["Wide", "Centered", "Compact"], key="layout_type")
            sidebar_width = st.slider("Ancho del sidebar", 200, 400, 280, key="sidebar_width")
            
        with theme_tab3:
            st.checkbox("Animaciones suaves", value=True, key="smooth_animations")
            st.checkbox("Sombras y profundidad", value=True, key="shadows")
            st.checkbox("Efectos hover", value=True, key="hover_effects")
    
    with col2:
        st.subheader("⚡ Estado del Sistema")
        st.metric("Módulos cargados", "6/6", "100%")
        st.metric("Memoria usada", "45%", "2%")
        st.metric("Rendimiento", "Óptimo", "0%")
        
        st.subheader("🔧 Acciones Rápidas")
        
        # BOTÓN 1: Reiniciar Session State (REQUIERE CONTRASEÑA)
        if 'show_password_reset_session' not in st.session_state:
            st.session_state.show_password_reset_session = False
            
        if not st.session_state.show_password_reset_session:
            if st.button("🔄 Reiniciar Session State", use_container_width=True, key="reset_session_btn"):
                st.session_state.show_password_reset_session = True
                st.rerun()
        
        if config_panel.show_password_modal("reset_session"):
            # Ejecutar acción de reinicio
            keys_to_delete = [key for key in st.session_state.keys() if not key.startswith('password') and not key.startswith('show_password')]
            for key in keys_to_delete:
                del st.session_state[key]
            st.success("✅ Session State reiniciado correctamente")
            st.rerun()
        
        # BOTÓN 2: Limpiar Cache (NO REQUIERE CONTRASEÑA - acción segura)
        if st.button("🗑️ Limpiar Cache", use_container_width=True, key="clear_cache_btn"):
            st.cache_data.clear()
            st.success("✅ Cache limpiado correctamente")
        
        # BOTÓN 3: Estado Completo (REQUIERE CONTRASEÑA)
        if 'show_password_show_state' not in st.session_state:
            st.session_state.show_password_show_state = False
            
        if not st.session_state.show_password_show_state:
            if st.button("📊 Estado Completo", use_container_width=True, key="show_state_btn"):
                st.session_state.show_password_show_state = True
                st.rerun()
        
        if config_panel.show_password_modal("show_state"):
            # Mostrar estado completo
            st.json({k: str(type(v)) for k, v in st.session_state.items()})
    
    # Configuración de funcionalidades
    st.subheader("🛠️ Configuración de Módulos")
    
    mod_col1, mod_col2, mod_col3 = st.columns(3)
    
    with mod_col1:
        st.markdown("**📊 Procesamiento**")
        st.slider("Tamaño máximo de archivo (MB)", 1, 500, 100, key="max_file_size")
        st.number_input("Límite de filas para análisis", 1000, 1000000, 50000, key="max_rows")
        
    with mod_col2:
        st.markdown("**⚡ Generación API**")
        # FRAMEWORKS AGREGADOS
        st.selectbox(
            "Framework API", 
            [
                "FastAPI",
                "Flask", 
                "Django REST Framework",
                "Express.js (Node.js)",
                "Spring Boot (Java)",
                "ASP.NET Core (C#)",
                "Gin (Go)",
                "Rocket (Rust)"
            ], 
            key="api_framework"
        )
        st.checkbox("Auto-documentación", value=True, key="auto_docs")
        st.checkbox("Validación automática", value=True, key="auto_validation")
        
    with mod_col3:
        st.markdown("**🗃️ Base de Datos**")
        # MONGODB AGREGADO
        st.selectbox(
            "Motor DB", 
            [
                "SQLite",
                "PostgreSQL",
                "MySQL",
                "MongoDB",
                "MariaDB",
                "SQL Server",
                "Oracle DB",
                "CouchDB",
                "Cassandra",
                "Redis"
            ], 
            key="db_engine"
        )
        st.checkbox("Backup automático", value=True, key="auto_backup")
        st.checkbox("Índices automáticos", value=True, key="auto_indexes")
    
    # Botones de acción
    st.markdown("---")
    action_col1, action_col2, action_col3 = st.columns(3)
    
    with action_col1:
        # BOTÓN: Guardar Configuración (NO REQUIERE CONTRASEÑA)
        if st.button("💾 Guardar Configuración", use_container_width=True, key="save_config_btn"):
            if config_panel.save_configuration():
                st.success("✅ Configuración guardada exitosamente!")
            
    with action_col2:
        # BOTÓN: Restablecer Valores (REQUIERE CONTRASEÑA)
        if 'show_password_reset_values' not in st.session_state:
            st.session_state.show_password_reset_values = False
            
        if not st.session_state.show_password_reset_values:
            if st.button("🔄 Restablecer Valores", use_container_width=True, key="reset_values_btn"):
                st.session_state.show_password_reset_values = True
                st.rerun()
        
        if config_panel.show_password_modal("reset_values"):
            # Restablecer valores predeterminados
            st.session_state.max_file_size = 100
            st.session_state.max_rows = 50000
            st.session_state.api_framework = "FastAPI"
            st.session_state.db_engine = "SQLite"
            st.success("✅ Valores restablecidos a predeterminados")
            st.rerun()
            
    with action_col3:
        # BOTÓN: Exportar Configuración (NO REQUIERE CONTRASEÑA)
        if st.button("📥 Exportar Configuración", use_container_width=True, key="export_config_btn"):
            if config_panel.save_configuration():
                try:
                    with open(config_panel.config_file, 'r') as f:
                        config_data = f.read()
                    st.download_button(
                        label="⬇️ Descargar Configuración JSON",
                        data=config_data,
                        file_name="app_config.json",
                        mime="application/json",
                        use_container_width=True
                    )
                except Exception as e:
                    st.error(f"Error exportando configuración: {e}")

if __name__ == "__main__":
    show()