#!/bin/bash
# Add translations for new languages to existing categories
# Usage: DIRECTUS_TOKEN=your_admin_token bash docs/add-category-translations.sh
#
# This script adds it-IT, es-ES, pt-BR, ru-RU translations to all categories.
# It reads existing categories from the API and creates missing translations.

API="https://api.dgray.io"
TOKEN="${DIRECTUS_TOKEN:?Set DIRECTUS_TOKEN environment variable}"

add_translation() {
    local category_id="$1" lang_code="$2" name="$3"

    curl -s -X POST "$API/items/categories_translations" \
        -H "Authorization: Bearer $TOKEN" \
        -H "Content-Type: application/json" \
        -d "{
            \"categories_id\": \"$category_id\",
            \"languages_code\": \"$lang_code\",
            \"name\": \"$name\"
        }" > /dev/null 2>&1
}

add_all_translations() {
    local category_id="$1"
    local name_it="$2" name_es="$3" name_pt="$4" name_ru="$5"

    add_translation "$category_id" "it-IT" "$name_it"
    add_translation "$category_id" "es-ES" "$name_es"
    add_translation "$category_id" "pt-BR" "$name_pt"
    add_translation "$category_id" "ru-RU" "$name_ru"
}

echo "=== Adding translations (it-IT, es-ES, pt-BR, ru-RU) ==="
echo ""

# Clean up orphaned translations (categories_id = null) from previous runs
echo "Cleaning up orphaned translations..."
ORPHANS=$(curl -s "$API/items/categories_translations?filter[categories_id][_null]=true&fields=id&limit=-1" \
    -H "Authorization: Bearer $TOKEN")
ORPHAN_IDS=$(echo "$ORPHANS" | grep -o '"id":[0-9]*' | cut -d: -f2 | tr '\n' ',' | sed 's/,$//')
if [ -n "$ORPHAN_IDS" ]; then
    curl -s -X DELETE "$API/items/categories_translations" \
        -H "Authorization: Bearer $TOKEN" \
        -H "Content-Type: application/json" \
        -d "[$ORPHAN_IDS]" > /dev/null 2>&1
    echo "  ✓ removed orphaned entries"
fi

# Fetch all categories to get their IDs (no status filter for admin)
echo "Fetching categories..."
CATEGORIES=$(curl -s "$API/items/categories?fields=id,slug&limit=-1" \
    -H "Authorization: Bearer $TOKEN")

get_id() {
    local slug="$1"
    echo "$CATEGORIES" | python3 -c "
import json, sys
data = json.load(sys.stdin).get('data', [])
for cat in data:
    if cat.get('slug') == '$slug':
        print(cat['id'])
        break
"
}

# ── 1. Electronics ──
echo "1/12 Electronics..."
ID=$(get_id "electronics")
add_all_translations "$ID" "Elettronica" "Electrónica" "Eletrônicos" "Электроника"

ID=$(get_id "phones")
add_all_translations "$ID" "Telefoni e Tablet" "Teléfonos y Tablets" "Celulares e Tablets" "Телефоны и планшеты"

ID=$(get_id "computers")
add_all_translations "$ID" "Computer e Accessori" "Ordenadores y Accesorios" "Computadores e Acessórios" "Компьютеры и аксессуары"

ID=$(get_id "tv-audio")
add_all_translations "$ID" "TV, Audio e Video" "TV, Audio y Vídeo" "TV, Áudio e Vídeo" "ТВ, аудио и видео"

ID=$(get_id "gaming")
add_all_translations "$ID" "Gaming e Console" "Gaming y Consolas" "Games e Consoles" "Игры и консоли"

ID=$(get_id "appliances")
add_all_translations "$ID" "Elettrodomestici" "Electrodomésticos" "Eletrodomésticos" "Бытовая техника"

ID=$(get_id "cameras")
add_all_translations "$ID" "Fotocamere e Fotografia" "Cámaras y Fotografía" "Câmeras e Fotografia" "Камеры и фотография"
echo "  ✓ done"

# ── 2. Vehicles ──
echo "2/12 Vehicles..."
ID=$(get_id "vehicles")
add_all_translations "$ID" "Veicoli" "Vehículos" "Veículos" "Транспорт"

ID=$(get_id "cars")
add_all_translations "$ID" "Auto" "Coches" "Carros" "Автомобили"

ID=$(get_id "motorcycles")
add_all_translations "$ID" "Moto" "Motos" "Motos" "Мотоциклы"

ID=$(get_id "bikes")
add_all_translations "$ID" "Biciclette ed E-Bike" "Bicicletas y E-Bikes" "Bicicletas e E-Bikes" "Велосипеды и электровелосипеды"

ID=$(get_id "vehicle-parts")
add_all_translations "$ID" "Ricambi e Accessori" "Recambios y Accesorios" "Peças e Acessórios" "Запчасти и аксессуары"

ID=$(get_id "boats")
add_all_translations "$ID" "Barche e Imbarcazioni" "Barcos y Embarcaciones" "Barcos e Embarcações" "Лодки и водный транспорт"
echo "  ✓ done"

# ── 3. Home & Garden ──
echo "3/12 Home & Garden..."
ID=$(get_id "home-garden")
add_all_translations "$ID" "Casa e Giardino" "Hogar y Jardín" "Casa e Jardim" "Дом и сад"

ID=$(get_id "furniture")
add_all_translations "$ID" "Mobili" "Muebles" "Móveis" "Мебель"

ID=$(get_id "kitchen")
add_all_translations "$ID" "Cucina" "Cocina" "Cozinha" "Кухня"

ID=$(get_id "garden")
add_all_translations "$ID" "Giardino e Outdoor" "Jardín y Exterior" "Jardim e Exterior" "Сад и отдых"

ID=$(get_id "tools")
add_all_translations "$ID" "Utensili e Officina" "Herramientas y Taller" "Ferramentas e Oficina" "Инструменты"

ID=$(get_id "decoration")
add_all_translations "$ID" "Decorazioni e Arte" "Decoración y Arte" "Decoração e Arte" "Декор и искусство"

ID=$(get_id "bathroom")
add_all_translations "$ID" "Bagno e Sanitari" "Baño y Sanitarios" "Banheiro" "Ванная"
echo "  ✓ done"

# ── 4. Fashion & Accessories ──
echo "4/12 Fashion..."
ID=$(get_id "fashion")
add_all_translations "$ID" "Moda e Accessori" "Moda y Accesorios" "Moda e Acessórios" "Мода и аксессуары"

ID=$(get_id "women")
add_all_translations "$ID" "Moda Donna" "Moda Mujer" "Moda Feminina" "Женская одежда"

ID=$(get_id "men")
add_all_translations "$ID" "Moda Uomo" "Moda Hombre" "Moda Masculina" "Мужская одежда"

ID=$(get_id "kids-fashion")
add_all_translations "$ID" "Moda Bambini" "Moda Infantil" "Moda Infantil" "Детская одежда"

ID=$(get_id "shoes")
add_all_translations "$ID" "Scarpe" "Zapatos" "Sapatos" "Обувь"

ID=$(get_id "watches-jewelry")
add_all_translations "$ID" "Orologi e Gioielli" "Relojes y Joyas" "Relógios e Joias" "Часы и украшения"

ID=$(get_id "bags")
add_all_translations "$ID" "Borse e Bagagli" "Bolsos y Equipaje" "Bolsas e Bagagem" "Сумки и багаж"
echo "  ✓ done"

# ── 5. Sports & Leisure ──
echo "5/12 Sports..."
ID=$(get_id "sports")
add_all_translations "$ID" "Sport e Tempo Libero" "Deportes y Ocio" "Esportes e Lazer" "Спорт и отдых"

ID=$(get_id "fitness")
add_all_translations "$ID" "Fitness e Palestra" "Fitness y Gimnasio" "Fitness e Academia" "Фитнес"

ID=$(get_id "outdoor-sports")
add_all_translations "$ID" "Escursionismo e Outdoor" "Senderismo y Outdoor" "Trilhas e Outdoor" "Туризм и походы"

ID=$(get_id "winter-sports")
add_all_translations "$ID" "Sport Invernali" "Deportes de Invierno" "Esportes de Inverno" "Зимний спорт"

ID=$(get_id "water-sports")
add_all_translations "$ID" "Sport Acquatici" "Deportes Acuáticos" "Esportes Aquáticos" "Водный спорт"

ID=$(get_id "team-sports")
add_all_translations "$ID" "Sport di Squadra" "Deportes de Equipo" "Esportes Coletivos" "Командный спорт"

ID=$(get_id "cycling")
add_all_translations "$ID" "Accessori Ciclismo" "Equipamiento Ciclismo" "Equipamento Ciclismo" "Велоаксессуары"
echo "  ✓ done"

# ── 6. Family & Kids ──
echo "6/12 Family & Kids..."
ID=$(get_id "family-kids")
add_all_translations "$ID" "Famiglia e Bambini" "Familia y Niños" "Família e Crianças" "Семья и дети"

ID=$(get_id "toys")
add_all_translations "$ID" "Giocattoli e Giochi" "Juguetes y Juegos" "Brinquedos e Jogos" "Игрушки и игры"

ID=$(get_id "baby")
add_all_translations "$ID" "Neonati e Prima Infanzia" "Bebé y Primera Infancia" "Bebê e Primeira Infância" "Для малышей"

ID=$(get_id "school")
add_all_translations "$ID" "Materiale Scolastico" "Material Escolar" "Material Escolar" "Школьные принадлежности"
echo "  ✓ done"

# ── 7. Books & Media ──
echo "7/12 Books & Media..."
ID=$(get_id "books-media")
add_all_translations "$ID" "Libri e Media" "Libros y Medios" "Livros e Mídia" "Книги и медиа"

ID=$(get_id "fiction")
add_all_translations "$ID" "Narrativa" "Ficción" "Ficção" "Художественная литература"

ID=$(get_id "nonfiction")
add_all_translations "$ID" "Saggistica e Scienze" "No Ficción y Ciencia" "Não Ficção e Ciência" "Нон-фикшн и наука"

ID=$(get_id "textbooks")
add_all_translations "$ID" "Libri di Testo e Corsi" "Libros de Texto y Cursos" "Livros Didáticos e Cursos" "Учебники и курсы"

ID=$(get_id "music-movies")
add_all_translations "$ID" "Musica, Film e Giochi" "Música, Películas y Juegos" "Música, Filmes e Jogos" "Музыка, фильмы и игры"
echo "  ✓ done"

# ── 8. Pets & Animals ──
echo "8/12 Pets..."
ID=$(get_id "pets")
add_all_translations "$ID" "Animali e Accessori" "Mascotas y Animales" "Animais e Acessórios" "Животные"

ID=$(get_id "pet-supplies")
add_all_translations "$ID" "Accessori per Animali" "Accesorios para Mascotas" "Acessórios para Animais" "Зоотовары"

ID=$(get_id "pet-adoption")
add_all_translations "$ID" "Adozione" "Adopción" "Adoção" "Усыновление"
echo "  ✓ done"

# ── 9. Jobs & Services ──
echo "9/12 Jobs..."
ID=$(get_id "jobs")
add_all_translations "$ID" "Lavoro e Servizi" "Empleo y Servicios" "Empregos e Serviços" "Работа и услуги"

ID=$(get_id "full-time")
add_all_translations "$ID" "Tempo Pieno" "Tiempo Completo" "Tempo Integral" "Полная занятость"

ID=$(get_id "part-time")
add_all_translations "$ID" "Part-Time e Lavoretti" "Tiempo Parcial y Minijobs" "Meio Período" "Частичная занятость"

ID=$(get_id "freelance")
add_all_translations "$ID" "Freelance e Remoto" "Freelance y Remoto" "Freelance e Remoto" "Фриланс и удалёнка"

ID=$(get_id "services")
add_all_translations "$ID" "Servizi e Artigianato" "Servicios y Oficios" "Serviços e Artesanato" "Услуги и ремесло"
echo "  ✓ done"

# ── 10. Real Estate ──
echo "10/12 Real Estate..."
ID=$(get_id "real-estate")
add_all_translations "$ID" "Immobili" "Inmuebles" "Imóveis" "Недвижимость"

ID=$(get_id "apartments")
add_all_translations "$ID" "Appartamenti" "Pisos" "Apartamentos" "Квартиры"

ID=$(get_id "houses")
add_all_translations "$ID" "Case" "Casas" "Casas" "Дома"

ID=$(get_id "rooms")
add_all_translations "$ID" "Stanze e Coinquilini" "Habitaciones y Pisos Compartidos" "Quartos e Repúblicas" "Комнаты и совместное проживание"

ID=$(get_id "commercial")
add_all_translations "$ID" "Commerciale" "Comercial" "Comercial" "Коммерческая недвижимость"
echo "  ✓ done"

# ── 11. Collectibles & Hobbies ──
echo "11/12 Collectibles..."
ID=$(get_id "collectibles")
add_all_translations "$ID" "Collezionismo e Hobby" "Coleccionismo y Hobbies" "Colecionáveis e Hobbies" "Коллекционирование и хобби"

ID=$(get_id "antiques")
add_all_translations "$ID" "Antiquariato" "Antigüedades" "Antiguidades" "Антиквариат"

ID=$(get_id "coins-stamps")
add_all_translations "$ID" "Monete e Francobolli" "Monedas y Sellos" "Moedas e Selos" "Монеты и марки"

ID=$(get_id "models")
add_all_translations "$ID" "Modellismo e Figurine" "Modelismo y Figuras" "Modelismo e Figuras" "Моделизм и фигурки"

ID=$(get_id "art-crafts")
add_all_translations "$ID" "Arte e Fatto a Mano" "Arte y Hecho a Mano" "Arte e Artesanato" "Искусство и хендмейд"
echo "  ✓ done"

# ── 12. Other ──
echo "12/12 Other..."
ID=$(get_id "other")
add_all_translations "$ID" "Altro" "Otros" "Outros" "Прочее"

ID=$(get_id "free-stuff")
add_all_translations "$ID" "Gratis" "Gratis" "Grátis" "Бесплатно"

ID=$(get_id "barter")
add_all_translations "$ID" "Baratto e Scambio" "Trueque e Intercambio" "Troca" "Обмен"

ID=$(get_id "lost-found")
add_all_translations "$ID" "Oggetti Smarriti" "Objetos Perdidos" "Achados e Perdidos" "Находки"
echo "  ✓ done"

echo ""
echo "=== Translation import complete! ==="
echo "4 languages × 71 categories = 284 translations added."
