#!/bin/bash
# Upload OCR dataset to Gitea generic packages
#
# Usage:
#   ./src/dataset_formatting/upload-dataset.sh [token]
#
# Environment variables:
#   GITEA_TOKEN - Gitea API token

set -e

GITEA_URL="https://seryus.ddns.net"
GITEA_ORG="unir"
PACKAGE_NAME="ocr-dataset-spanish"
VERSION="1.0.0"
DATASET_DIR="src/dataset_hf"
TARBALL="dataset-${VERSION}.tar.gz"

# Get token
TOKEN="${1:-${GITEA_TOKEN}}"
if [ -z "$TOKEN" ]; then
    echo "Error: No token provided"
    echo "Usage: $0 [token]"
    echo "  or set GITEA_TOKEN environment variable"
    exit 1
fi

# Check dataset exists
if [ ! -d "$DATASET_DIR" ]; then
    echo "Error: Dataset not found at $DATASET_DIR"
    echo "Run: python src/convert_to_hf_dataset.py first"
    exit 1
fi

# Create tarball
echo "Creating tarball..."
tar -czvf "$TARBALL" -C "$DATASET_DIR" .
echo "Created: $TARBALL ($(du -h $TARBALL | cut -f1))"

# Upload
echo "Uploading to Gitea packages..."
echo "  URL: $GITEA_URL/api/packages/$GITEA_ORG/generic/$PACKAGE_NAME/$VERSION/$TARBALL"

HTTP_CODE=$(curl -sS -w "%{http_code}" -o /tmp/upload_response.txt \
    -X PUT \
    -H "Authorization: token $TOKEN" \
    -H "Content-Type: application/octet-stream" \
    --data-binary "@$TARBALL" \
    "$GITEA_URL/api/packages/$GITEA_ORG/generic/$PACKAGE_NAME/$VERSION/$TARBALL")

if [ "$HTTP_CODE" = "201" ] || [ "$HTTP_CODE" = "200" ]; then
    echo "Success! Dataset uploaded."
    echo "Download URL: $GITEA_URL/api/packages/$GITEA_ORG/generic/$PACKAGE_NAME/$VERSION/$TARBALL"
    rm "$TARBALL"
elif [ "$HTTP_CODE" = "409" ]; then
    echo "Package version already exists (HTTP 409)"
    rm "$TARBALL"
else
    echo "Error: Upload failed with HTTP $HTTP_CODE"
    cat /tmp/upload_response.txt
    rm "$TARBALL"
    exit 1
fi
