#!/usr/bin/env bash

SNIPPET_DIR="$HOME/git/4837173"
SNIPPET_ID="4837173"
BASE_URL="https://gitlab.com/-/snippets/$SNIPPET_ID/raw/main"

cd "$SNIPPET_DIR" || { echo "❌ No se pudo acceder al snippet local"; exit 1; }

guess_extension() {
    head -n 20 | grep -qE '^\s*\{' && echo "json" && return
    head -n 20 | grep -qE '^# ' && echo "md" && return
    head -n 20 | grep -qE '^#!/bin/(bash|sh)' && echo "sh" && return
    head -n 20 | grep -qE '<[^>]+>' && echo "html" && return
    head -n 20 | grep -qE '^\s*(def |class )' && echo "py" && return
    echo "txt"
}

copy_to_clipboard() {
    if command -v wl-copy &>/dev/null; then
        echo -n "$1" | wl-copy
        echo "📋 Copiado al portapapeles con wl-copy"
    elif command -v xclip &>/dev/null; then
        echo -n "$1" | xclip -selection clipboard
        echo "📋 Copiado al portapapeles con xclip"
    else
        echo "⚠️ No se pudo copiar al portapapeles (falta wl-copy/xclip)"
    fi
}

sync_with_remote() {
    git pull --rebase || {
        echo "❌ Error al sincronizar con el remoto. ¿Tienes cambios sin guardar?"
        exit 1
    }
}

clean_if_needed() {
    local max_files=9
    local file_count
    file_count=$(ls -1 | wc -l)

    if [ "$file_count" -ge "$max_files" ]; then
        oldest=$(ls -tr | head -n 1)
        echo "⚠️ Límite alcanzado. Borrando: $oldest"
        git rm "$oldest"
        git commit -m "Borrado $oldest (limpieza automática)"
        git push
    fi
}

# --- PIPE: stdin ---
if [ ! -t 0 ] && [ "$#" -eq 0 ]; then
    EXT=$(guess_extension <&0)
    FILE="paste_$(date '+%Y-%m-%d_%H-%M-%S').$EXT"
    sync_with_remote
    clean_if_needed
    cat - > "$FILE"
    git add "$FILE"
    git commit -m "Añadido paste por pipe: $FILE"
    git push
    LINK="$BASE_URL/$FILE"
    echo "🔗 $LINK"
    copy_to_clipboard "$LINK"
    exit 0
fi

# --- INTERACTIVO sin argumentos ---
if [ "$#" -eq 0 ]; then
    FILE="paste_$(date '+%Y-%m-%d_%H-%M-%S').txt"
    nano "$FILE"
    sync_with_remote
    clean_if_needed
    git add "$FILE"
    git commit -m "Añadido paste manual: $FILE"
    git push
    LINK="$BASE_URL/$FILE"
    echo "🔗 $LINK"
    copy_to_clipboard "$LINK"
    exit 0
fi

# --- ARCHIVOS como argumentos ---
sync_with_remote
clean_if_needed

for src in "$@"; do
    filename=$(basename "$src")
    cp "$src" "$filename" || { echo "❌ No se pudo copiar '$src'"; exit 1; }
    git add "$filename"
done

git commit -m "Añadido(s): $*" || echo "⚠️ Nada nuevo que comitear"
git push

for src in "$@"; do
    filename=$(basename "$src")
    LINK="$BASE_URL/$filename"
    echo "🔗 $LINK"
    copy_to_clipboard "$LINK"
done

