#!/usr/bin/env bash
set -euo pipefail

# VERSION=0.0
# VERDATE="September 08, 2026"

QUOTES_FOLDER="/home/ubuntu/folders/quotes"
ALIASES="$QUOTES_FOLDER/.aliases.json"
THRESHOLD="85"

similarity() {
    python3 - "$1" "$2" <<'PY'
from rapidfuzz.fuzz import ratio
import sys

print(int(ratio(sys.argv[1], sys.argv[2])))
PY
}

NC="\033[0m"
BOLD="\033[1m"
YELLOW="\033[0;33m"
RED="\033[0;31m"
GREEN="\033[0;32m"
BLUE="\033[0;34m"
MAGENTA="\033[0;35m"

qsortSay() {
    local msg msgType
    msg=""
    msgType="$1"

    case "$msgType" in
        1) msg="${BLUE}${BOLD}[qs:INFO]${NC}" ;;
        2) msg="${RED}${BOLD}[qs:ERR ]${NC}" ;;
        3) msg="${YELLOW}${BOLD}[qs:WARN]${NC}" ;;
        4) msg="${MAGENTA}${BOLD}[qs:EXTR]${NC}" ;;
        5) msg="${GREEN}${BOLD}[qs:RNM ]${NC}" ;;
    esac

    printf '%b\n' "$msg $2"
}

while IFS= read -r -d '' file; do
    [[ "$file" == *".png" ]] || continue
    # qsortSay 1 "$file"

    # get username
    fileBn="${file##*/}"
    stem="${fileBn%%.*}"

    username="${stem##*_}"
    # echo "$username"

    # pipe to alias
    if _alias="$(jq -r --arg username "$username" '.[$username] // empty' "$ALIASES")" && [[ -n "$_alias" ]]; then
        username="$_alias"
    else
        # fuzzy alias
        bestAlias=""
        bestScore=0

        while IFS= read -r aliasTest; do
            score=$(similarity "$aliasTest" "$username")

            if (( score > bestScore )); then
                bestScore="$score"
                bestAlias="$aliasTest"
            elif (( score >= 93 )); then
                bestScore="$score"
                bestAlias="$aliasTest"
                break
            fi
        done < <(jq -r 'keys[]' "$ALIASES")

        bestAliasValue="$(jq -r --arg v "$bestAlias" '.[$v]' "$ALIASES")"
        if (( bestScore >= THRESHOLD )); then
            qsortSay 5 "fuzzy: $username -> $bestAliasValue ($bestScore%)"
            username="$bestAliasValue"
        fi
    fi
    qsortSay 1 "$fileBn -> $username"

    # make dirs
    usernameDir="$QUOTES_FOLDER/$username"
    [[ -d "$usernameDir" ]] || ( mkdir -p "$usernameDir" && qsortSay 4 "made $usernameDir" )

    # organize quote
    [[ -e "$usernameDir/$file" ]] || mv -- "$file" "$usernameDir"

    # echo "$username"
done < <(find "$QUOTES_FOLDER" -maxdepth 1 -type f -print0 -iname "*.png")
