#!/bin/bash
# x402-layer Skill Installer
# Usage: curl -fsSL https://api.x402layer.cc/skill/x402-layer/install | bash

set -e

SKILL_NAME="x402-layer"
INSTALL_DIR="${1:-./$SKILL_NAME}"

echo "🚀 Installing x402-layer skill..."
echo "   Install directory: $INSTALL_DIR"

# Create directory
mkdir -p "$INSTALL_DIR/scripts"
mkdir -p "$INSTALL_DIR/references"

# Download main files
echo "📥 Downloading SKILL.md..."
curl -fsSL "https://api.x402layer.cc/skill/x402-layer/SKILL.md" -o "$INSTALL_DIR/SKILL.md"

echo "📥 Downloading requirements.txt..."
curl -fsSL "https://api.x402layer.cc/skill/x402-layer/requirements.txt" -o "$INSTALL_DIR/requirements.txt"

# Download all scripts
SCRIPTS=(
    "pay_base.py"
    "pay_solana.py"
    "consume_credits.py"
    "consume_product.py"
    "check_credits.py"
    "recharge_credits.py"
    "create_endpoint.py"
    "manage_endpoint.py"
    "topup_endpoint.py"
    "discover_marketplace.py"
    "list_on_marketplace.py"
    "wallet_signing.py"
    "awal_bridge.py"
    "awal_cli.py"
    "network_selection.py"
    "solana_signing.py"
    "manage_webhook.py"
    "verify_webhook_payment.py"
    "erc8004_wallet_client.py"
    "register_agent.py"
    "list_agents.py"
    "list_my_endpoints.py"
    "update_agent.py"
    "submit_feedback.py"
)

echo "📥 Downloading scripts..."
for script in "${SCRIPTS[@]}"; do
    curl -fsSL "https://api.x402layer.cc/skill/x402-layer/scripts/$script" -o "$INSTALL_DIR/scripts/$script"
    echo "   ✓ $script"
done

# Download references
REFERENCES=(
    "agentic-endpoints.md"
    "credit-based.md"
    "marketplace.md"
    "pay-per-request.md"
    "payment-signing.md"
    "webhooks-verification.md"
    "agent-registry-reputation.md"
)

echo "📥 Downloading references..."
for ref in "${REFERENCES[@]}"; do
    curl -fsSL "https://api.x402layer.cc/skill/x402-layer/references/$ref" -o "$INSTALL_DIR/references/$ref"
    echo "   ✓ $ref"
done

# Install Python dependencies
echo ""
echo "📦 Installing Python dependencies..."
pip install -r "$INSTALL_DIR/requirements.txt" --quiet

echo ""
echo "✅ x402-layer skill installed successfully!"
echo ""
echo "📍 Location: $INSTALL_DIR"
echo ""
echo "🔧 Next steps:"
echo "   1. Set wallet environment variables:"
echo "      # Private key mode"
echo "      export X402_AUTH_MODE='private-key'"
echo "      export PRIVATE_KEY='0x...'"
echo "      export WALLET_ADDRESS='0x...'"
echo ""
echo "      # AWAL mode (preferred if configured)"
echo "      export X402_AUTH_MODE='awal'"
echo "      export X402_USE_AWAL=1"
echo ""
echo "   2. Try it out:"
echo "      python $INSTALL_DIR/scripts/discover_marketplace.py"
echo ""
echo "📚 Docs: https://studio.x402layer.cc/docs/agentic-access/openclaw-skill"
