-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
629 lines (500 loc) · 25.1 KB
/
main.py
File metadata and controls
629 lines (500 loc) · 25.1 KB
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
"""
SoundVault CLI - Interfaz de línea de comandos para gestionar álbumes musicales
"""
import logging
import sys
from typing import Optional, Callable
from datetime import datetime
from pathlib import Path
# Añadir src al path para imports
sys.path.insert(0, str(Path(__file__).parent / 'src'))
from config import (
RESET, GREEN, YELLOW, CYAN, RED, BLUE, MAGENTA,
MOOD_EMOJIS, PLATFORM_EMOJIS, VALID_PLATFORMS, VALID_MOODS,
LOG_FILE, LOG_LEVEL
)
from models import Album
from validators import (
validate_int_range, validate_float_range, validate_platform,
validate_date, validate_yes_no
)
from database import (
init_db, add_album, get_album_by_id, update_album, delete_album,
list_albums, get_statistics, get_top_albums, search_albums,
backup_database, DatabaseError
)
from import_export import export_to_csv, export_to_json, import_from_csv, import_from_json
# Configurar logging
Path(LOG_FILE).parent.mkdir(exist_ok=True)
logging.basicConfig(
level=LOG_LEVEL,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler(LOG_FILE, encoding='utf-8'),
logging.StreamHandler()
]
)
logger = logging.getLogger(__name__)
def prompt(text: str, example: Optional[str] = None, optional: bool = False,
validator: Optional[Callable[[str], bool]] = None) -> Optional[str]:
"""Solicita input al usuario con validación"""
while True:
display = f"{text}" + (f" (Ej: {example})" if example else "")
if optional:
display += " (opcional)"
display += ": "
value = input(display).strip()
if not value and optional:
return None
if validator:
if validator(value):
return value
else:
print(f"{RED}❌ Entrada inválida, intenta de nuevo.{RESET}")
else:
if value:
return value
elif optional:
return None
else:
print(f"{RED}❌ No puede estar vacío.{RESET}")
def print_album(album: Album) -> None:
"""Imprime un álbum formateado"""
mood_emoji = MOOD_EMOJIS.get(album.mood, "")
platform_emoji = PLATFORM_EMOJIS.get(album.platform, "")
relisten_emoji = "🔁" if album.relisten else "❌"
print(f"\n{CYAN}[{album.id}]{RESET} {BLUE}{album.album_name}{RESET} ({album.release_year}) - {GREEN}{album.artists}{RESET}")
print(f" Género: {album.genre} | Estilo: {album.style} | Mood: {album.mood} {mood_emoji}")
print(f" {YELLOW}⭐ {album.stars}/5{RESET} {CYAN}💯 {album.decimal_rating}/10{RESET} Reescucha: {relisten_emoji}")
print(f" Plataforma: {album.platform} {platform_emoji} Fecha: {album.listened_date}")
if album.favorite_song:
print(f" 🎵 Canción favorita: {YELLOW}{album.favorite_song}{RESET}")
if album.review:
print(f" Review: {album.review}")
print("-" * 70)
def add_album_cli() -> None:
"""Interfaz CLI para añadir un álbum"""
try:
print(f"\n{MAGENTA}🎵 Nuevo álbum{RESET}\n" + "-" * 30)
album_name = prompt("Nombre del álbum", example="OK Computer")
artists = prompt("Artista(s) (separa múltiples con ';')", example="Radiohead")
release_year = int(prompt("Año de salida", example="1997",
validator=lambda v: v.isdigit()))
genre = prompt("Género", example="Rock")
style = prompt("Estilo / Subgénero", example="Alternative Rock")
stars = int(prompt("Rating en estrellas (1–5)", example="5",
validator=validate_int_range(1, 5)))
decimal_rating = float(prompt("Rating decimal (0–10)", example="9.6",
validator=validate_float_range(0, 10)))
# Mostrar opciones de mood como ejemplos
print(f"\n{CYAN}Moods (ejemplos, puedes escribir lo que quieras):{RESET}")
for i, mood in enumerate(VALID_MOODS, 1):
emoji = MOOD_EMOJIS.get(mood, "")
print(f" • {mood} {emoji}")
mood = prompt("Mood / Estado de ánimo", example="Chill")
relisten_input = prompt("¿Lo volverías a escuchar? (y/n)", example="y",
validator=validate_yes_no)
relisten = relisten_input.lower() in ['y', 'yes', 's', 'si']
# Mostrar opciones de plataforma
print(f"\n{CYAN}Plataformas (elige número u escribe otra):{RESET}")
for i, plat in enumerate(VALID_PLATFORMS, 1):
emoji = PLATFORM_EMOJIS.get(plat, "")
print(f" {i}. {plat} {emoji}")
platform_input = prompt("Plataforma (número o nombre)", example="1 o Spotify")
# Si es un número, seleccionar de la lista
if platform_input.isdigit() and 1 <= int(platform_input) <= len(VALID_PLATFORMS):
platform = VALID_PLATFORMS[int(platform_input) - 1]
else:
# Permitir escribir cualquier plataforma
platform = platform_input
# Fecha de escucha
print(f"\n{CYAN}Fecha de escucha:{RESET}")
print("1. Usar hoy")
print("2. Ingresar manualmente (YYYY-MM-DD)")
choice = input("> ").strip()
if choice == "2":
listened_date = prompt("Ingresa la fecha (YYYY-MM-DD)",
example=datetime.today().strftime("%Y-%m-%d"),
validator=validate_date)
else:
listened_date = datetime.today().strftime("%Y-%m-%d")
review = prompt("Review", optional=True)
favorite_song = prompt("¿Cuál fue tu canción favorita del álbum?", optional=True)
album = Album(
album_name=album_name,
artists=artists,
release_year=release_year,
genre=genre,
style=style,
stars=stars,
decimal_rating=decimal_rating,
mood=mood,
relisten=relisten,
platform=platform,
review=review,
favorite_song=favorite_song,
listened_date=listened_date
)
album_id = add_album(album)
print(f"\n{GREEN}✅ Álbum guardado correctamente con ID: {album_id}{RESET}\n")
except DatabaseError as e:
print(f"\n{RED}❌ Error de base de datos: {e}{RESET}\n")
logger.error(f"Error al añadir álbum: {e}")
except Exception as e:
print(f"\n{RED}❌ Error inesperado: {e}{RESET}\n")
logger.error(f"Error inesperado al añadir álbum: {e}")
def list_albums_cli() -> None:
"""Lista todos los álbumes"""
try:
albums = list_albums()
if not albums:
print(f"\n{RED}⚠ No hay álbumes guardados.{RESET}\n")
return
print(f"\n{MAGENTA}🎵 Álbumes guardados ({len(albums)} total){RESET}\n" + "=" * 70)
for album in albums:
print_album(album)
# Pausa para que el usuario pueda leer
input(f"\n{YELLOW}Presiona Enter para volver al menú...{RESET}")
except DatabaseError as e:
print(f"\n{RED}❌ Error de base de datos: {e}{RESET}\n")
logger.error(f"Error al listar álbumes: {e}")
def search_albums_cli() -> None:
"""Búsqueda de álbumes por término"""
try:
search_term = prompt("Término de búsqueda (busca en nombre, artista, género, estilo, review)")
if not search_term:
return
albums = search_albums(search_term)
if not albums:
print(f"\n{RED}⚠ No se encontraron álbumes.{RESET}\n")
return
print(f"\n{MAGENTA}🔍 Resultados de búsqueda ({len(albums)} encontrados){RESET}\n" + "=" * 70)
for album in albums:
print_album(album)
# Pausa para que el usuario pueda leer
input(f"\n{YELLOW}Presiona Enter para volver al menú...{RESET}")
except DatabaseError as e:
print(f"\n{RED}❌ Error de base de datos: {e}{RESET}\n")
def filter_albums_cli() -> None:
"""Filtra álbumes con múltiples criterios"""
try:
print(f"\n{MAGENTA}🔍 Filtrar álbumes{RESET}\n" + "-" * 30)
print("Deja en blanco los filtros que no quieras usar\n")
artist = prompt("Artista", optional=True)
platform = prompt("Plataforma", optional=True)
year_str = prompt("Año", optional=True)
year = int(year_str) if year_str and year_str.isdigit() else None
genre = prompt("Género", optional=True)
mood = prompt("Mood", optional=True)
min_rating_str = prompt("Rating mínimo (0-10)", optional=True)
min_rating = float(min_rating_str) if min_rating_str else None
max_rating_str = prompt("Rating máximo (0-10)", optional=True)
max_rating = float(max_rating_str) if max_rating_str else None
albums = list_albums(
filter_artist=artist,
filter_platform=platform,
filter_year=year,
filter_genre=genre,
filter_mood=mood,
min_rating=min_rating,
max_rating=max_rating
)
if not albums:
print(f"\n{RED}⚠ No hay álbumes que coincidan con los filtros.{RESET}\n")
return
print(f"\n{MAGENTA}📋 Álbumes filtrados ({len(albums)} encontrados){RESET}\n" + "=" * 70)
for album in albums:
print_album(album)
# Pausa para que el usuario pueda leer
input(f"\n{YELLOW}Presiona Enter para volver al menú...{RESET}")
except DatabaseError as e:
print(f"\n{RED}❌ Error de base de datos: {e}{RESET}\n")
def edit_album_cli() -> None:
"""Edita un álbum existente"""
try:
album_id_str = prompt("ID del álbum a editar")
if not album_id_str or not album_id_str.isdigit():
print(f"{RED}❌ ID inválido{RESET}")
return
album_id = int(album_id_str)
album = get_album_by_id(album_id)
if not album:
print(f"{RED}❌ No se encontró el álbum con ID {album_id}{RESET}")
return
print(f"\n{CYAN}Álbum actual:{RESET}")
print_album(album)
print(f"\n{YELLOW}Ingresa los nuevos valores (Enter para mantener el actual){RESET}\n")
album_name = prompt(f"Nombre [{album.album_name}]", optional=True) or album.album_name
artists = prompt(f"Artista(s) [{album.artists}]", optional=True) or album.artists
year_input = prompt(f"Año [{album.release_year}]", optional=True)
release_year = int(year_input) if year_input and year_input.isdigit() else album.release_year
genre = prompt(f"Género [{album.genre}]", optional=True) or album.genre
style = prompt(f"Estilo [{album.style}]", optional=True) or album.style
stars_input = prompt(f"Estrellas [{album.stars}]", optional=True,
validator=lambda v: not v or validate_int_range(1, 5)(v))
stars = int(stars_input) if stars_input else album.stars
rating_input = prompt(f"Rating decimal [{album.decimal_rating}]", optional=True,
validator=lambda v: not v or validate_float_range(0, 10)(v))
decimal_rating = float(rating_input) if rating_input else album.decimal_rating
mood = prompt(f"Mood [{album.mood}]", optional=True) or album.mood
relisten_input = prompt(f"Reescuchar [{'y' if album.relisten else 'n'}]",
optional=True, validator=lambda v: not v or validate_yes_no(v))
relisten = relisten_input.lower() in ['y', 'yes', 's', 'si'] if relisten_input else album.relisten
# Mostrar plataformas disponibles para editar
print(f"\n{CYAN}Plataformas (elige número u escribe otra):{RESET}")
for i, plat in enumerate(VALID_PLATFORMS, 1):
emoji = PLATFORM_EMOJIS.get(plat, "")
print(f" {i}. {plat} {emoji}")
platform_input = prompt(f"Plataforma [{album.platform}]", optional=True)
if platform_input:
# Si es un número, seleccionar de la lista
if platform_input.isdigit() and 1 <= int(platform_input) <= len(VALID_PLATFORMS):
platform = VALID_PLATFORMS[int(platform_input) - 1]
else:
# Permitir escribir cualquier plataforma
platform = platform_input
else:
platform = album.platform
listened_date_input = prompt(f"Fecha [{album.listened_date}]", optional=True,
validator=lambda v: not v or validate_date(v))
listened_date = listened_date_input or album.listened_date
review = prompt(f"Review [{album.review or 'Sin review'}]", optional=True)
if review is None:
review = album.review
favorite_song = prompt(f"Canción favorita [{album.favorite_song or 'Ninguna'}]", optional=True)
if favorite_song is None:
favorite_song = album.favorite_song
updated_album = Album(
id=album_id,
album_name=album_name,
artists=artists,
release_year=release_year,
genre=genre,
style=style,
stars=stars,
decimal_rating=decimal_rating,
mood=mood,
relisten=relisten,
platform=platform,
review=review,
favorite_song=favorite_song,
listened_date=listened_date
)
if update_album(updated_album):
print(f"\n{GREEN}✅ Álbum actualizado correctamente{RESET}\n")
else:
print(f"\n{RED}❌ No se pudo actualizar el álbum{RESET}\n")
except DatabaseError as e:
print(f"\n{RED}❌ Error de base de datos: {e}{RESET}\n")
except Exception as e:
print(f"\n{RED}❌ Error: {e}{RESET}\n")
def delete_album_cli() -> None:
"""Elimina un álbum"""
try:
album_id_str = prompt("ID del álbum a eliminar")
if not album_id_str or not album_id_str.isdigit():
print(f"{RED}❌ ID inválido{RESET}")
return
album_id = int(album_id_str)
album = get_album_by_id(album_id)
if not album:
print(f"{RED}❌ No se encontró el álbum con ID {album_id}{RESET}")
return
print(f"\n{CYAN}Álbum a eliminar:{RESET}")
print_album(album)
confirm = prompt(f"{RED}¿Estás seguro? Esta acción no se puede deshacer (y/n){RESET}",
validator=validate_yes_no)
if confirm.lower() not in ['y', 'yes', 's', 'si']:
print(f"{YELLOW}Operación cancelada{RESET}")
return
if delete_album(album_id):
print(f"\n{GREEN}✅ Álbum eliminado correctamente{RESET}\n")
else:
print(f"\n{RED}❌ No se pudo eliminar el álbum{RESET}\n")
except DatabaseError as e:
print(f"\n{RED}❌ Error de base de datos: {e}{RESET}\n")
def show_statistics() -> None:
"""Muestra estadísticas de la colección"""
try:
stats = get_statistics()
print(f"\n{MAGENTA}📊 Estadísticas de tu colección{RESET}\n" + "=" * 50)
print(f"\n{CYAN}General:{RESET}")
print(f" Total de álbumes: {stats['total_albums']}")
if stats['avg_stars']:
print(f" Promedio estrellas: {YELLOW}{stats['avg_stars']:.2f}/5{RESET}")
if stats['avg_decimal']:
print(f" Promedio rating: {CYAN}{stats['avg_decimal']:.2f}/10{RESET}")
print(f" Álbumes para reescuchar: {stats['relisten_count']}")
if stats['by_platform']:
print(f"\n{CYAN}Por plataforma:{RESET}")
for platform, count in stats['by_platform']:
emoji = PLATFORM_EMOJIS.get(platform, "")
print(f" {platform} {emoji}: {count}")
if stats['by_mood']:
print(f"\n{CYAN}Por mood:{RESET}")
for mood, count in stats['by_mood']:
emoji = MOOD_EMOJIS.get(mood, "")
print(f" {mood} {emoji}: {count}")
if stats['top_genres']:
print(f"\n{CYAN}Top 5 géneros:{RESET}")
for genre, count in stats['top_genres']:
print(f" {genre}: {count}")
print()
# Pausa para que el usuario pueda leer
input(f"{YELLOW}Presiona Enter para continuar...{RESET}")
except DatabaseError as e:
print(f"\n{RED}❌ Error de base de datos: {e}{RESET}\n")
def show_top_albums() -> None:
"""Muestra los mejores álbumes"""
try:
print(f"\n{CYAN}Ordenar por:{RESET}")
print("1. Rating decimal (0-10)")
print("2. Estrellas (1-5)")
choice = input("> ").strip()
rating_type = "decimal" if choice == "1" else "stars"
limit_str = prompt("¿Cuántos álbumes quieres ver?", example="10")
limit = int(limit_str) if limit_str and limit_str.isdigit() else 10
albums = get_top_albums(limit=limit, by_rating=rating_type)
if not albums:
print(f"\n{RED}⚠ No hay álbumes guardados.{RESET}\n")
return
rating_label = "decimal" if rating_type == "decimal" else "estrellas"
print(f"\n{MAGENTA}🏆 Top {len(albums)} álbumes (por {rating_label}){RESET}\n" + "=" * 70)
for i, album in enumerate(albums, 1):
print(f"\n{YELLOW}#{i}{RESET}")
print_album(album)
# Pausa para que el usuario pueda leer
input(f"\n{YELLOW}Presiona Enter para volver al menú...{RESET}")
except DatabaseError as e:
print(f"\n{RED}❌ Error de base de datos: {e}{RESET}\n")
def export_data_cli() -> None:
"""Exporta datos a CSV o JSON"""
try:
print(f"\n{CYAN}Formato de exportación:{RESET}")
print("1. CSV")
print("2. JSON")
choice = input("> ").strip()
albums = list_albums()
if not albums:
print(f"\n{RED}⚠ No hay álbumes para exportar.{RESET}\n")
return
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
if choice == "1":
filepath = f"data/albums_export_{timestamp}.csv"
if export_to_csv(albums, filepath):
print(f"\n{GREEN}✅ Exportado a {filepath}{RESET}\n")
else:
print(f"\n{RED}❌ Error al exportar{RESET}\n")
elif choice == "2":
filepath = f"data/albums_export_{timestamp}.json"
if export_to_json(albums, filepath):
print(f"\n{GREEN}✅ Exportado a {filepath}{RESET}\n")
else:
print(f"\n{RED}❌ Error al exportar{RESET}\n")
else:
print(f"{RED}Opción inválida{RESET}")
except Exception as e:
print(f"\n{RED}❌ Error: {e}{RESET}\n")
def import_data_cli() -> None:
"""Importa datos desde CSV o JSON"""
try:
print(f"\n{YELLOW}⚠ ADVERTENCIA: Esto añadirá los álbumes del archivo a tu colección.{RESET}")
print(f"{YELLOW}No se eliminarán los álbumes existentes.{RESET}\n")
filepath = prompt("Ruta del archivo a importar", example="data/albums.csv")
if not Path(filepath).exists():
print(f"\n{RED}❌ El archivo no existe{RESET}\n")
return
# Crear backup antes de importar
print(f"\n{CYAN}Creando backup...{RESET}")
backup_file = backup_database()
print(f"{GREEN}✅ Backup creado: {backup_file}{RESET}\n")
if filepath.endswith('.csv'):
imported, failed = import_from_csv(filepath)
elif filepath.endswith('.json'):
imported, failed = import_from_json(filepath)
else:
print(f"{RED}❌ Formato no soportado. Usa .csv o .json{RESET}")
return
print(f"\n{GREEN}✅ Importación completada:{RESET}")
print(f" Álbumes importados: {imported}")
print(f" Álbumes fallidos: {failed}\n")
except Exception as e:
print(f"\n{RED}❌ Error: {e}{RESET}\n")
def backup_cli() -> None:
"""Crea un backup manual de la base de datos"""
try:
backup_file = backup_database()
print(f"\n{GREEN}✅ Backup creado: {backup_file}{RESET}\n")
except DatabaseError as e:
print(f"\n{RED}❌ Error al crear backup: {e}{RESET}\n")
def main() -> None:
"""Menú principal de la aplicación"""
try:
init_db()
logger.info("Aplicación iniciada")
while True:
# ASCII Art Header
print(f"\n{CYAN}")
print(r" ███████╗ ██████╗ ██╗ ██╗███╗ ██╗██████╗ ██╗ ██╗ █████╗ ██╗ ██╗██╗ ████████╗ ╔════════╗")
print(r" ██╔════╝██╔═══██╗██║ ██║████╗ ██║██╔══██╗██║ ██║██╔══██╗██║ ██║██║ ╚══██╔══╝ ║ ▓▓▓▓▓▓ ║")
print(r" ███████╗██║ ██║██║ ██║██╔██╗ ██║██║ ██║██║ ██║███████║██║ ██║██║ ██║ ║ ▓╔══╗▓ ║")
print(r" ╚════██║██║ ██║██║ ██║██║╚██╗██║██║ ██║╚██╗ ██╔╝██╔══██║██║ ██║██║ ██║ ║ ▓║🎵║▓ ║")
print(r" ███████║╚██████╔╝╚██████╔╝██║ ╚████║██████╔╝ ╚████╔╝ ██║ ██║╚██████╔╝███████╗██║ ║ ▓╚══╝▓ ║")
print(r" ╚══════╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═══╝╚═════╝ ╚═══╝ ╚═╝ ╚═╝ ╚═════╝ ╚══════╝╚═╝ ║ ▓▓▓▓▓▓ ║")
print(r" ╚════════╝")
print(f"{RESET}")
print(f"{YELLOW} 🎵 Tu Colección Musical Segura 🎵 {RESET}")
print(f"{CYAN}{'─' * 100}{RESET}")
print(f"\n{MAGENTA}Gestión de álbumes:{RESET}")
print(" 1. ➕ Añadir un álbum")
print(" 2. 📋 Listar todos los álbumes")
print(" 3. 🔍 Buscar álbumes")
print(" 4. 🔎 Filtrar álbumes (avanzado)")
print(" 5. ✏️ Editar un álbum")
print(" 6. 🗑️ Eliminar un álbum")
print(f"\n{MAGENTA}Estadísticas y análisis:{RESET}")
print(" 7. 📊 Ver estadísticas")
print(" 8. 🏆 Top álbumes")
print(f"\n{MAGENTA}Importar/Exportar:{RESET}")
print(" 9. 📤 Exportar datos (CSV/JSON)")
print(" 10. 📥 Importar datos (CSV/JSON)")
print(" 11. 💾 Crear backup")
print(f"\n{MAGENTA}Otros:{RESET}")
print(" 0. 🚪 Salir")
choice = input(f"\n{CYAN}Selecciona una opción >{RESET} ").strip()
if choice == "1":
add_album_cli()
elif choice == "2":
list_albums_cli()
elif choice == "3":
search_albums_cli()
elif choice == "4":
filter_albums_cli()
elif choice == "5":
edit_album_cli()
elif choice == "6":
delete_album_cli()
elif choice == "7":
show_statistics()
elif choice == "8":
show_top_albums()
elif choice == "9":
export_data_cli()
elif choice == "10":
import_data_cli()
elif choice == "11":
backup_cli()
elif choice == "0":
print(f"\n{GREEN}👋 ¡Hasta luego!{RESET}\n")
logger.info("Aplicación cerrada")
break
else:
print(f"{RED}❌ Opción inválida. Intenta de nuevo.{RESET}")
except KeyboardInterrupt:
print(f"\n\n{YELLOW}⚠ Aplicación interrumpida por el usuario{RESET}\n")
logger.info("Aplicación interrumpida por el usuario")
except Exception as e:
print(f"\n{RED}❌ Error crítico: {e}{RESET}\n")
logger.critical(f"Error crítico: {e}", exc_info=True)
if __name__ == "__main__":
main()