"""Forensic analysis of misclassified samples."""
import json, os

PROJECT = r"C:\Users\Administrator\Documents\fl_control"
with open(os.path.join(PROJECT, "data", "sample_index.json"), "r", encoding="utf-8") as f:
    d = json.load(f)

samples = d["samples"]

# --- DRUMLOOPS ---
drumloops = [s for s in samples if s.get("role") == "drumloop"]
print(f"DRUMLOOPS ({len(drumloops)} total)")
print(f"{'Orig filename':<55s} {'Dur':>5s} {'Onset':>5s} {'Centr':>7s} {'Low':>5s} {'Mid':>5s} {'High':>5s} {'Tonal':>5s} {'Key':>5s} {'Char':>10s}")
print("-" * 120)
for s in drumloops[:50]:
    orig = s.get("original_name", "?")[:54]
    dur = s["signal"]["duration"]
    onc = s["perceptual"]["onset_count"]
    cent = s["signal"]["spectral_centroid_mean"]
    low = s["signal"]["low_energy_ratio"]
    mid = s["signal"]["mid_energy_ratio"]
    high = s["signal"]["high_energy_ratio"]
    ton = s["musical"]["is_tonal"]
    key = s["musical"]["key"]
    char = s["character"]
    print(f"{orig:<55s} {dur:5.1f} {onc:5d} {cent:7.0f} {low:5.2f} {mid:5.2f} {high:5.2f} {str(ton):>5s} {key:>5s} {char:>10s}")

# --- ONESHOTS ---
oneshots = [s for s in samples if s.get("role") == "oneshot"]
print(f"\nONESHOTS ({len(oneshots)} total)")
print(f"{'Orig filename':<55s} {'Dur':>5s} {'Onset':>5s} {'Centr':>7s} {'Low':>5s} {'Mid':>5s} {'High':>5s} {'Tonal':>5s} {'Key':>5s} {'Char':>10s}")
print("-" * 120)
for s in oneshots[:40]:
    orig = s.get("original_name", "?")[:54]
    dur = s["signal"]["duration"]
    onc = s["perceptual"]["onset_count"]
    cent = s["signal"]["spectral_centroid_mean"]
    low = s["signal"]["low_energy_ratio"]
    mid = s["signal"]["mid_energy_ratio"]
    high = s["signal"]["high_energy_ratio"]
    ton = s["musical"]["is_tonal"]
    key = s["musical"]["key"]
    char = s["character"]
    print(f"{orig:<55s} {dur:5.1f} {onc:5d} {cent:7.0f} {low:5.2f} {mid:5.2f} {high:5.2f} {str(ton):>5s} {key:>5s} {char:>10s}")

# --- Summary: folder source of drumloops ---
print(f"\n\nDRUMLOOP ORIGINS:")
from collections import Counter
origins = Counter()
for s in drumloops:
    path = s.get("original_path", "")
    parts = path.replace("\\", "/").split("/")
    # Find the category folder
    for i, p in enumerate(parts):
        if "reggaeton" in p.lower() and i+1 < len(parts):
            origins[parts[i+1]] += 1
            break
for k, v in origins.most_common():
    print(f"  {k:40s} {v:4d}")

# --- Summary: folder source of oneshots ---
print(f"\nONESHOT ORIGINS:")
origins2 = Counter()
for s in oneshots:
    path = s.get("original_path", "")
    parts = path.replace("\\", "/").split("/")
    for i, p in enumerate(parts):
        if "reggaeton" in p.lower() and i+1 < len(parts):
            origins2[parts[i+1]] += 1
            break
for k, v in origins2.most_common():
    print(f"  {k:40s} {v:4d}")
