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

# PyPI Land Grab — claim package names via tentacle builder
ROOT="$(cd "$(dirname "$0")" && pwd)"
TOKEN="pypi-AgEIcHlwaS5vcmcCJGQyYTlhMjhjLTM2MmMtNDVlNi05NDBiLTg4YWQ3OTk2NWNiMAACKlszLCIyZjk3ZTBmNS04NzRiLTQ3NWMtYjdmZi1mOWMzOGEzNDA2NzUiXQAABiBqECyWOiMmbkiRWH0FTlUKvRW5jZVN6YU635g8P33PEg"

# === MISSED TOOLS ===
TOOLS=(stemsplit codefixer scanurl fetchurl video2text)

# === RICHEST BRANDS IN THE WORLD ===
LUXURY=(louisvuitton hermes chanel rolex dior burberry tiffany versace armani balenciaga fendi valentino givenchy saintlaurent omega montblanc bvlgari moncler celine loewe)
TECH=(apple google microsoft amazon samsung nvidia meta tesla intel oracle adobe salesforce spotify uber airbnb stripe openai palantir)
AUTO=(ferrari porsche bmw mercedes lamborghini bentley rollsroyce maserati bugatti mclaren astonmartin pagani)
FINANCE=(visa mastercard jpmorgan goldmansachs amex)
FOOD=(pepsi starbucks mcdonalds redbull hennessy domperignon moet veuveclicquot patron macallan)
MORE=(zara adidas puma newbalance converse supreme offwhite bottegaveneta vancleefarpels patekphilippe audemarspiguet rimowa chopard swarovski tiffanyandco)

ALL=("${TOOLS[@]}" "${LUXURY[@]}" "${TECH[@]}" "${AUTO[@]}" "${FINANCE[@]}" "${FOOD[@]}" "${MORE[@]}")

CLAIMED=()
FAILED=()
TAKEN=()

echo "=== PyPI Land Grab ==="
echo "Total targets: ${#ALL[@]}"
echo ""

for name in "${ALL[@]}"; do
    echo -n "[$name] "

    # Build tentacle (unset TWINE vars so build_tentacle.sh doesn't try to upload)
    OUT=$(unset TWINE_USERNAME TWINE_PASSWORD; "$ROOT/build_tentacle.sh" "$name" 2>&1)
    if [ $? -ne 0 ]; then
        echo "BUILD FAIL"
        FAILED+=("$name:build")
        continue
    fi

    DIST_DIR="$ROOT/tentacles/$name/dist"

    # Upload with token
    UPLOAD_OUT=$(TWINE_USERNAME="__token__" TWINE_PASSWORD="$TOKEN" python3 -m twine upload "$DIST_DIR"/* 2>&1)
    RC=$?

    if [ $RC -eq 0 ]; then
        echo "CLAIMED"
        CLAIMED+=("$name")
    elif echo "$UPLOAD_OUT" | grep -qi "already exists\|File already exists"; then
        echo "TAKEN"
        TAKEN+=("$name")
    elif echo "$UPLOAD_OUT" | grep -qi "too similar\|not allowed\|Invalid\|isn.t allowed"; then
        echo "BLOCKED"
        FAILED+=("$name:blocked")
    elif echo "$UPLOAD_OUT" | grep -qi "429\|rate.limit\|Too Many"; then
        echo "RATE LIMITED — pausing 60s"
        FAILED+=("$name:ratelimit")
        sleep 60
    elif echo "$UPLOAD_OUT" | grep -qi "403\|Forbidden"; then
        echo "403 FORBIDDEN"
        FAILED+=("$name:forbidden")
    else
        echo "FAIL: $(echo "$UPLOAD_OUT" | tail -1)"
        FAILED+=("$name:unknown")
    fi

    sleep 2
done

echo ""
echo "=== RESULTS ==="
echo "CLAIMED (${#CLAIMED[@]}): ${CLAIMED[*]}"
echo "ALREADY TAKEN (${#TAKEN[@]}): ${TAKEN[*]}"
echo "FAILED (${#FAILED[@]}): ${FAILED[*]}"
