#!/bin/bash
set -euo pipefail

# Configuration
GIST_RAW_BASE="https://opengist.resetrix.work/weehong/f0d940c3c1214bf5b7996195199fdc09/raw/HEAD"
CONFIG_FILES=(
    ".alias"
    ".func"
    ".pathrc"
    ".sourcerc"
    ".vimrc"
    ".zshrc"
    ".config/starship.toml"
)
PLAN_BUILD_SKILL_TARGET="$HOME/.claude/skills/plan-build/SKILL.md"

echo "Starting configuration download..."
download_failed=0

for f in "${CONFIG_FILES[@]}"; do
    # Remove the leading dot for the URL path
    remote_name="${f#.}"
    [[ "$f" == ".config/starship.toml" ]] && remote_name="starship.toml"
    url="$GIST_RAW_BASE/$remote_name"
    target="$HOME/$f"
    tmp="${target}.tmp.$$"

    echo "Downloading $f..."
    mkdir -p "$(dirname "$target")"
    
    # Use -f to fail silently on server errors, -s for silent, -L to follow redirects
    if curl -fsSL "$url" -o "$tmp" && mv "$tmp" "$target"; then
        echo "Successfully updated $target"
    else
        rm -f "$tmp"
        echo "Error: Failed to download $f from $url" >&2
        download_failed=1
    fi
done

echo "Downloading Claude Code plan-build workflow..."
mkdir -p "$(dirname "$PLAN_BUILD_SKILL_TARGET")"
skill_tmp="${PLAN_BUILD_SKILL_TARGET}.tmp.$$"
if curl -fsSL "$GIST_RAW_BASE/orchestrate-loop.md" -o "$skill_tmp" && mv "$skill_tmp" "$PLAN_BUILD_SKILL_TARGET"; then
    echo "Successfully updated $PLAN_BUILD_SKILL_TARGET"
else
    rm -f "$skill_tmp"
    echo "Error: Failed to download the plan-build workflow" >&2
    download_failed=1
fi

if [ "$download_failed" -ne 0 ]; then
    echo "Configuration download completed with errors." >&2
    exit 1
fi

echo "Done! All configuration files have been replaced."
