"""
Show statistics from the analysis index.
"""
import sys
import os
import json

PROJECT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
os.chdir(PROJECT)


def main():
    index_path = os.path.join(PROJECT, "data", "sample_index.json")

    if not os.path.exists(index_path):
        print("ERROR: No existe data/sample_index.json")
        print("       Ejecuta primero 1_ANALIZAR.bat")
        return

    with open(index_path, "r", encoding="utf-8") as f:
        index = json.load(f)

    samples = index["samples"]
    valid = [s for s in samples if "error" not in s]

    print("=" * 60)
    print(f"  ESTADISTICAS DE LA BIBLIOTECA ({len(valid)} samples)")
    print("=" * 60)

    # Roles
    roles = {}
    for s in valid:
        r = s.get("role", "?")
        roles[r] = roles.get(r, 0) + 1

    print("\n  Roles:")
    max_count = max(roles.values()) if roles else 1
    for role, count in sorted(roles.items(), key=lambda x: -x[1]):
        bar_len = int(40 * count / max_count)
        print(f"    {role:12s} {count:4d}  {'█' * bar_len}")

    # Characters
    chars = {}
    for s in valid:
        c = s.get("character", "?")
        chars[c] = chars.get(c, 0) + 1

    print("\n  Caracteres sonoros:")
    max_count = max(chars.values()) if chars else 1
    for char, count in sorted(chars.items(), key=lambda x: -x[1]):
        bar_len = int(40 * count / max_count)
        print(f"    {char:12s} {count:4d}  {'█' * bar_len}")

    # Keys
    keys = {}
    for s in valid:
        k = s.get("musical", {}).get("key", "X")
        keys[k] = keys.get(k, 0) + 1

    print("\n  Tonalidades:")
    for key, count in sorted(keys.items(), key=lambda x: -x[1])[:15]:
        print(f"    {key:5s} {count:4d}")

    # Tempo distribution
    tempos = [s.get("perceptual", {}).get("tempo", 0) for s in valid]
    tempos_nonzero = [t for t in tempos if t > 0]
    if tempos_nonzero:
        print(f"\n  Tempo:")
        print(f"    Rango: {min(tempos_nonzero):.0f} - {max(tempos_nonzero):.0f} BPM")
        print(f"    Promedio: {sum(tempos_nonzero) / len(tempos_nonzero):.0f} BPM")

    # LUFS distribution
    lufs = [s.get("perceptual", {}).get("lufs", 0) for s in valid]
    lufs_valid = [l for l in lufs if l > -70]
    if lufs_valid:
        print(f"\n  Loudness (LUFS):")
        print(f"    Rango: {min(lufs_valid):.1f} a {max(lufs_valid):.1f} LUFS")
        print(f"    Promedio: {sum(lufs_valid) / len(lufs_valid):.1f} LUFS")

    # Tonal vs atonal
    tonal = sum(1 for s in valid if s.get("musical", {}).get("is_tonal", False))
    atonal = len(valid) - tonal
    print(f"\n  Tonalidad:")
    print(f"    Tonal: {tonal} ({100 * tonal / len(valid):.0f}%)")
    print(f"    Atonal: {atonal} ({100 * atonal / len(valid):.0f}%)")

    # One-shot vs loop
    oneshot = sum(1 for s in valid if s.get("musical", {}).get("is_oneshot", False))
    loops = sum(1 for s in valid if s.get("musical", {}).get("is_loop", False))
    print(f"\n  Tipo:")
    print(f"    One-shots: {oneshot}")
    print(f"    Loops: {loops}")
    print(f"    Otros: {len(valid) - oneshot - loops}")

    print("\n" + "=" * 60)

    # Show samples per role for quick reference
    print("\n  EJEMPLOS POR ROL:")
    by_role = {}
    for s in valid:
        role = s.get("role", "?")
        if role not in by_role:
            by_role[role] = []
        by_role[role].append(s)

    for role in sorted(by_role.keys()):
        samples_list = by_role[role][:5]
        print(f"\n  [{role}] ({len(by_role[role])} total)")
        for s in samples_list:
            key = s.get("musical", {}).get("key", "X")
            char = s.get("character", "?")
            bpm = s.get("perceptual", {}).get("tempo", 0)
            print(f"    {s.get('new_name', '?'):50s} key={key:5s} bpm={bpm:5.0f} char={char}")


if __name__ == "__main__":
    main()
