#!/bin/bash
# TMDB to Emby metadata updater
# Fetches Chinese episode names/overviews from TMDB API and updates Emby SQLite DB

TMDB_API="https://api.themoviedb.org/3"
# TMDB API key (free, read-only)
TMDB_KEY="eyJhbGciOiJIUzI1NiJ9.eyJhdWQiOiI3MmJiNzMwMTRmMWQ1MTBjOGE4NjA3ZDViOGQ1MzA4YSIsIm5iZiI6MTczOTcwMjE0NC4wNTksInN1YiI6IjY3YjI2NjAwNjRkODEzMjI3NjA5NjI3NyIsInNjb3BlcyI6WyJhcGlfcmVhZCJdLCJ2ZXJzaW9uIjoxfQ.placeholder"

SSH_CMD="ssh -i /tmp/koipy_key -o StrictHostKeyChecking=no root@155.103.67.95"
DB="/data/emby/config/data/library.db"

TOTAL_UPDATED=0

update_season() {
    local series_id=$1
    local tmdb_id=$2
    local season=$3
    local show_name=$4
    
    echo "  Fetching S$(printf '%02d' $season) from TMDB..."
    
    # Fetch from TMDB API
    local url="https://api.themoviedb.org/3/tv/${tmdb_id}/season/${season}?language=zh-CN"
    local json=$(curl -s "$url" -H "Authorization: Bearer eyJhbGciOiJIUzI1NiJ9.eyJhdWQiOiI3MmJiNzMwMTRmMWQ1MTBjOGE4NjA3ZDViOGQ1MzA4YSIsIm5iZiI6MTczOTcwMjE0NC4wNTksInN1YiI6IjY3YjI2NjAwNjRkODEzMjI3NjA5NjI3NyIsInNjb3BlcyI6WyJhcGlfcmVhZCJdLCJ2ZXJzaW9uIjoxfQ.placeholder" -H "accept: application/json" 2>/dev/null)
    
    # Check if valid response
    if echo "$json" | grep -q '"status_code"'; then
        echo "    ⚠️  Season $season not found on TMDB, skipping"
        return
    fi
    
    local count=$(echo "$json" | python3 -c "import sys,json; d=json.load(sys.stdin); print(len(d.get('episodes',[])))" 2>/dev/null)
    if [ -z "$count" ] || [ "$count" = "0" ]; then
        echo "    ⚠️  No episodes found, skipping"
        return
    fi
    
    echo "    Found $count episodes"
    
    # Generate SQL updates
    local sql=$(echo "$json" | python3 -c "
import sys, json

data = json.load(sys.stdin)
episodes = data.get('episodes', [])
series_id = $series_id
season = $season

sqls = []
for ep in episodes:
    num = ep.get('episode_number', 0)
    name = ep.get('name', '').replace(\"'\", \"''\")
    overview = (ep.get('overview', '') or '').replace(\"'\", \"''\")[:500]
    
    if name:
        if overview:
            sqls.append(f\"UPDATE MediaItems SET Name='{name}', Overview='{overview}' WHERE SeriesId={series_id} AND type=8 AND ParentIndexNumber={season} AND IndexNumber={num};\")
        else:
            sqls.append(f\"UPDATE MediaItems SET Name='{name}' WHERE SeriesId={series_id} AND type=8 AND ParentIndexNumber={season} AND IndexNumber={num};\")

print('\n'.join(sqls))
" 2>/dev/null)
    
    if [ -z "$sql" ]; then
        echo "    ⚠️  No valid data to update"
        return
    fi
    
    local update_count=$(echo "$sql" | wc -l | tr -d ' ')
    
    # Execute SQL via SSH
    echo "$sql" | $SSH_CMD "sqlite3 '$DB'" 2>/dev/null
    
    echo "    ✅ Updated $update_count episodes"
    TOTAL_UPDATED=$((TOTAL_UPDATED + update_count))
}

echo "========================================="
echo "TMDB → Emby Metadata Updater"
echo "========================================="

# 1. 汪汪队立大功
echo ""
echo "📺 [1/8] 汪汪队立大功 (SeriesId=229, TMDB=57532)"
for s in 1 3 4 5 11; do
    update_season 229 57532 $s "汪汪队立大功"
done

# 2. 小猪佩奇
echo ""
echo "📺 [2/8] 小猪佩奇 (SeriesId=228, TMDB=12225)"
for s in 1 2 3 4 5; do
    update_season 228 12225 $s "小猪佩奇"
done

# 3. 海底小纵队
echo ""
echo "📺 [3/8] 海底小纵队 (SeriesId=869, TMDB=44204)"
for s in 1 2 3 4; do
    update_season 869 44204 $s "海底小纵队"
done

# 4. 小恐龙大冒险
echo ""
echo "📺 [4/8] 小恐龙大冒险 (SeriesId=871, TMDB=82700)"
for s in 1 2 3; do
    update_season 871 82700 $s "小恐龙大冒险"
done

# 5. 小马宝莉
echo ""
echo "📺 [5/8] 小马宝莉 (SeriesId=1375, TMDB=21159)"
for s in 1 2 3 4 7 9; do
    update_season 1375 21159 $s "小马宝莉"
done

# 6. 动物神探队
echo ""
echo "📺 [6/8] 动物神探队 (SeriesId=146, TMDB=195407)"
for s in 1 2 3 4 5 6 7; do
    update_season 146 195407 $s "动物神探队"
done

# 7. 安全警长啦咘啦哆
echo ""
echo "📺 [7/8] 安全警长啦咘啦哆 (SeriesId=230, TMDB=219799)"
for s in 1 2 3; do
    update_season 230 219799 $s "安全警长啦咘啦哆"
done

# 8. 啦咘啦哆大战羚羚羊
echo ""
echo "📺 [8/8] 啦咘啦哆大战羚羚羊 (SeriesId=231, TMDB=253041)"
for s in 1 2; do
    update_season 231 253041 $s "啦咘啦哆大战羚羚羊"
done

echo ""
echo "========================================="
echo "✅ Total episodes updated: $TOTAL_UPDATED"
echo "========================================="

# Trigger Emby library refresh
echo ""
echo "🔄 Triggering Emby library refresh..."
$SSH_CMD "curl -s -X POST 'http://127.0.0.1:8096/emby/Library/Refresh?api_key=e3e52b1dcb8b47c39d46b5256bf87081'" 2>/dev/null
echo ""
echo "✅ Done!"
