#!/usr/bin/env bash
# gitea_push_directory — Inicializa git en un directorio y lo sube a un repo Gitea existente

gitea_push_directory() {
    local directory="$1"
    local owner="$2"
    local repo="$3"
    local branch="${4:-main}"

    if [[ -z "${GITEA_URL:-}" ]]; then
        echo "gitea_push_directory: GITEA_URL no está seteada" >&2
        return 1
    fi
    if [[ -z "${GITEA_TOKEN:-}" ]]; then
        echo "gitea_push_directory: GITEA_TOKEN no está seteado" >&2
        return 1
    fi
    if [[ -z "$directory" || -z "$owner" || -z "$repo" ]]; then
        echo "gitea_push_directory: se requieren directory, owner y repo" >&2
        return 1
    fi
    if [[ ! -d "$directory" ]]; then
        echo "gitea_push_directory: directorio '$directory' no existe" >&2
        return 1
    fi

    # Construir URL con credenciales embebidas para autenticación
    local gitea_host
    gitea_host=$(echo "$GITEA_URL" | sed 's|https\?://||')
    local remote_url="https://${GITEA_TOKEN}@${gitea_host}/${owner}/${repo}.git"
    local display_url="https://***@${gitea_host}/${owner}/${repo}.git"

    echo "gitea_push_directory: procesando '$directory' → '$owner/$repo' (rama: $branch)..." >&2

    # Añadir registry.db al .gitignore local si existe en el directorio
    if [[ -f "$directory/registry.db" ]]; then
        echo "gitea_push_directory: añadiendo registry.db al .gitignore..." >&2
        if [[ ! -f "$directory/.gitignore" ]] || ! grep -qxF "registry.db" "$directory/.gitignore"; then
            echo "registry.db" >> "$directory/.gitignore"
        fi
    fi

    # Gestionar estado del repositorio git
    if [[ -d "$directory/.git" ]]; then
        local existing_remote
        existing_remote=$(git -C "$directory" remote get-url origin 2>/dev/null || echo "")

        if [[ -z "$existing_remote" ]]; then
            echo "gitea_push_directory: añadiendo remote origin..." >&2
            git -C "$directory" remote add origin "$remote_url"
        else
            # Comparar remote sin token para detectar si apunta al mismo repo
            local clean_existing
            clean_existing=$(echo "$existing_remote" | sed 's|https://[^@]*@||;s|https://||')
            local clean_target="${gitea_host}/${owner}/${repo}.git"

            if [[ "$clean_existing" != "$clean_target" ]]; then
                echo "gitea_push_directory: remote apunta a otro destino ('$clean_existing'), actualizando..." >&2
                git -C "$directory" remote set-url origin "$remote_url"
            else
                echo "gitea_push_directory: remote ya apunta al destino correcto, actualizando token..." >&2
                git -C "$directory" remote set-url origin "$remote_url"
            fi
        fi
    else
        echo "gitea_push_directory: inicializando nuevo repositorio git..." >&2
        git -C "$directory" init
        git -C "$directory" remote add origin "$remote_url"
    fi

    # Configurar rama por defecto
    git -C "$directory" checkout -B "$branch" 2>/dev/null || true

    # Añadir y commitear cambios si los hay
    git -C "$directory" add -A

    local git_status
    git_status=$(git -C "$directory" status --porcelain)

    if [[ -n "$git_status" ]]; then
        echo "gitea_push_directory: commiteando cambios..." >&2
        git -C "$directory" -c user.email="agent@fn-registry" -c user.name="fn-registry agent" \
            commit -m "chore: sync from fn-registry agent"
    else
        echo "gitea_push_directory: sin cambios pendientes, solo haciendo push..." >&2
    fi

    echo "gitea_push_directory: haciendo push a $display_url..." >&2
    git -C "$directory" push --set-upstream origin "$branch" --force-with-lease 2>&1 \
        | sed "s|${GITEA_TOKEN}|***|g" >&2 \
        || git -C "$directory" push --set-upstream origin "$branch" 2>&1 \
            | sed "s|${GITEA_TOKEN}|***|g" >&2

    echo "gitea_push_directory: push completado a '$owner/$repo' rama '$branch'" >&2
}
