"""Forensic analysis of misclassified samples."""
import json, os, re
from collections import Counter

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"]

# --- Analyze filename patterns in misclassified ---
print("=" * 70)
print("  PATRONES DE NOMBRE EN 'DRUMLOOPS'")
print("=" * 70)

# Extract Midilatino stems
ml_stems = Counter()
for s in samples:
    if s.get("role") != "drumloop":
        continue
    name = s.get("original_name", "")
    # Midilatino pattern: Midilatino_Name_Key_Min_BPM_Stem.wav
    if "Midilatino" in name or "midilatino" in name:
        # Extract the stem type (last part before .wav)
        parts = name.replace(".wav", "").replace(".flac", "").replace(".mp3", "")
        # Try to find stem keywords
        for kw in ["Drums", "Bass", "Lead", "Pad", "Pluck", "Arp", "Vocal",
                    "Vox", "Guitar", "Rhodes", "Piano", "Synth", "Reese",
                    "Texture", "Chords", "Reverse", "Fx", "Accent", "Harp",
                    "Keys", "Bell", "Loop", "Stem", "Snare", "Kick", "Hat",
                    "Perc", "Shaker", "Hi", "808"]:
            if kw.lower() in parts.lower():
                ml_stems[kw] += 1
                break
        else:
            # No stem keyword found - it's the full mix
            ml_stems["FULL_MIX"] += 1

print("\nMidilatino stem types in 'drumloop':")
for k, v in ml_stems.most_common():
    print(f"  {k:15s} {v:4d}")

# --- SS_RNBL patterns ---
print("\n\nSentimientoLatino SS_RNBL patterns:")
ss_stems = Counter()
for s in samples:
    name = s.get("original_name", "")
    if "SS_RNBL" in name:
        # Extract type: SS_RNBL_Song_Stem_Type.wav
        parts = name.replace(".wav", "").split("_")
        if len(parts) >= 4:
            stem_type = parts[3] if parts[3] not in ("One", "Shot") else "_".join(parts[3:5])
            ss_stems[stem_type] += 1

for k, v in ss_stems.most_common():
    print(f"  {k:20s} {v:4d}")

# --- All filename keywords ---
print("\n\nAll filename role keywords across library:")
role_keywords = Counter()
for s in samples:
    name = s.get("original_name", "").lower()
    for kw in ["kick", "snare", "hi-hat", "hihat", "hat", "bass", "808",
                "lead", "pad", "pluck", "arp", "vocal", "vox", "fx",
                "perc", "drum", "loop", "fill", "guitar", "piano", "rhodes",
                "synth", "bell", "brass", "string", "reese", "texture",
                "chord", "shaker", "tambourine", "conga", "rim"]:
        if kw in name:
            role_keywords[kw] += 1

for k, v in role_keywords.most_common(25):
    print(f"  {k:15s} {v:4d}")
