#!/bin/bash

# --- KONFIGŪRACIJA ---
SOURCE_DIR="/home/seederis/Torrents/downloads/Torrent"
DEST_DIR="/home/seederis/Torrents/downloads/Torrent/sutvarkyti"
LOG_DB="/home/seederis/Torrents/downloads/Torrent/processed_list.txt"
LOG_JSON="/home/seederis/Torrents/downloads/Torrent/processed.json"
TITLES_DB="/home/seederis/Torrents/downloads/Torrent/titles_db.txt"
PYTHON_SCRIPT="/home/seederis/Torrents/downloads/Torrent/zvairas.py"
UPDATE_URL="https://185.221.202.161/darbas/peertube/update_dle2.php"

GRN='\033[0;32m'; BLU='\033[0;34m'; YEL='\033[1;33m'; CYN='\033[0;36m'; MAG='\033[0;35m'; RED='\033[0;31m'; NC='\033[0m'

mkdir -p "$DEST_DIR"
touch "$TITLES_DB" "$LOG_DB"

SKIP_SESSION_LIST=""

echo -e "${BLU}>>> KONVEJERIS PALEISTAS. Originalai SAUGOMI.${NC}"

while true; do
    file=$(find "$SOURCE_DIR" -maxdepth 1 -type f \( -name "*.mkv" -o -name "*.mp4" \) ! -name "*.!qB" | while read -r f; do
        if ! grep -Fq "$f" "$LOG_DB"; then echo "$f"; break; fi
    done)

    if [ -z "$file" ]; then
        echo -e "${YEL}Laukiu naujų failų (60s)...${NC}"
        sleep 60
        
        # Tikriname paskutinį kartą prieš uždarant
        file_retry=$(find "$SOURCE_DIR" -maxdepth 1 -type f \( -name "*.mkv" -o -name "*.mp4" \) ! -name "*.!qB" | while read -r f; do if ! grep -Fq "$f" "$LOG_DB"; then echo "$f"; break; fi; done)
        
        if [ -z "$file_retry" ]; then
            echo -e "${RED}Darbas baigtas. Generuojame JSON ir pranešame svetainei...${NC}"
            echo "[" > "$LOG_JSON"
            sed 's/.*/  "&"/' "$LOG_DB" | sed '$!s/$/,/' >> "$LOG_JSON"
            echo "]" >> "$LOG_JSON"
            curl -sk "$UPDATE_URL" > /dev/null
            echo -e "${GRN}Svetainė informuota. Išsijungiu.${NC}"
            exit 0
        fi
        file="$file_retry"
    fi

    filename=$(basename "$file")
    clean_name=$(echo "$filename" | grep -oiP '^.*?(?=\.S\d|S\d|\.\d{1,2}x|\s\d)' | head -n 1)
    [ -z "$clean_name" ] && clean_name="${filename%.*}"

    if [[ "$SKIP_SESSION_LIST" == *"$clean_name"* ]]; then
        echo -e "${YEL}Praleidžiama sesijoje:${NC} $filename"
        echo "$file" >> "$LOG_DB"
        continue
    fi

    DB_LINE=$(grep -i "^${clean_name}=" "$TITLES_DB" | head -n 1)
    
    if [ -n "$DB_LINE" ]; then
        data=$(echo "$DB_LINE" | cut -d'=' -f2-)
        KNOWN_TITLE=$(echo "$data" | cut -d'|' -f1)
        CURRENT_AID=$(echo "$data" | cut -d'|' -f2)
        echo -e "${GRN}Atpažinta:${NC} $KNOWN_TITLE (ID: $CURRENT_AID)"
    else
        echo -e "\n${MAG}===============================================${NC}"
        echo -e "${CYN}APTINKTAS NAUJAS:${NC} $filename"
        mkvmerge -J "$file" | jq -r '.tracks[] | select(.type == "audio") | "  ID \(.id): [\(.properties.language // "??")] \(.properties.track_name // "No Name")"' 2>/dev/null
        
        echo -n -e "${YEL}LT pavadinimas (s - skip, ok - ignore):${NC} "; read user_input < /dev/tty
        
        if [ "$user_input" == "s" ]; then
            SKIP_SESSION_LIST="$SKIP_SESSION_LIST|$clean_name"
            echo "$file" >> "$LOG_DB"; continue
        elif [ "$user_input" == "ok" ]; then
            echo "${clean_name}=SKIP|0" >> "$TITLES_DB"
            echo "$file" >> "$LOG_DB"; continue
        else
            echo -n -e "${YEL}LT Audio ID:${NC} "; read aid < /dev/tty
            echo "${clean_name}=${user_input}|${aid}" >> "$TITLES_DB"
            KNOWN_TITLE="$user_input"; CURRENT_AID="$aid"
        fi
    fi

    se_code=$(echo "$filename" | grep -oiP 'S\d{1,2}E\d{1,2}' | head -n 1 | tr '[:lower:]' '[:upper:]')
    out_name="${KNOWN_TITLE} ${se_code}"
    final_file="${DEST_DIR}/${out_name}.mkv"

    echo -e "${CYN}Ruošiamas kėlimui:${NC} $out_name..."
    
    # Sukuriame "hardlink" (neužima papildomos vietos, bet leidžia manipuliuoti metaduomenimis)
    ln -f "$file" "$final_file"
    
    # Sutvarkome takelius tik tame laikiname faile (propedit veikia tiesiogiai)
    prop_id=$((CURRENT_AID + 1))
    mkvpropedit "$final_file" --edit track:all --set flag-default=0 &> /dev/null
    mkvpropedit "$final_file" --edit "track:$prop_id" --set flag-default=1 --set language=lit &> /dev/null
    
    # Paleidžiame Python kėlimą
    python3 "$PYTHON_SCRIPT"
    
    # !!! SVARBU: Triname TIK laikiną failą iš 'sutvarkyti' aplanko
    rm -f "$final_file"
    
    # Įrašome originalą į logus, kad antrą kartą nebekeltų
    echo "$file" >> "$LOG_DB"
    echo -e "${GRN}Baigta. Originalas liko: $filename${NC}"
    echo "-----------------------------------------------"
done
