#!/usr/bin/env bash
# Kie.ai API Key Setup Script
# Stores the API key securely in the system keychain (macOS) or encrypted file

set -euo pipefail

KIE_CONFIG_DIR="${HOME}/.config/kie-ai"
KIE_CONFIG_FILE="${KIE_CONFIG_DIR}/config"
KEYCHAIN_SERVICE="kie-ai-api"

echo "=== Kie.ai API Key Setup ==="
echo ""
echo "Get your API key at: https://kie.ai/api-key"
echo ""

# Check if already configured
existing_key=""
if [[ "$(uname)" == "Darwin" ]]; then
    existing_key=$(security find-generic-password -s "$KEYCHAIN_SERVICE" -w 2>/dev/null || true)
elif [[ -f "$KIE_CONFIG_FILE" ]]; then
    existing_key=$(grep -oP 'api_key=\K.*' "$KIE_CONFIG_FILE" 2>/dev/null || true)
fi

if [[ -n "$existing_key" ]]; then
    masked="${existing_key:0:8}...${existing_key: -4}"
    echo "Existing API key found: $masked"
    echo ""
    read -rp "Replace existing key? (y/N): " replace
    if [[ "$replace" != "y" && "$replace" != "Y" ]]; then
        echo "Keeping existing key."
        exit 0
    fi
fi

# Read the new API key
read -rsp "Enter your Kie.ai API key: " api_key
echo ""

if [[ -z "$api_key" ]]; then
    echo "Error: API key cannot be empty."
    exit 1
fi

# Validate the key by checking credits
echo "Validating API key..."
response=$(curl -s -w "\n%{http_code}" -H "Authorization: Bearer $api_key" \
    "https://api.kie.ai/api/v1/chat/credit" 2>/dev/null || true)

http_code=$(echo "$response" | tail -1)
body=$(echo "$response" | head -1)

if [[ "$http_code" == "200" ]]; then
    credits=$(echo "$body" | python3 -c "import sys,json; print(json.load(sys.stdin).get('data','?'))" 2>/dev/null || echo "?")
    echo "Valid! Remaining credits: $credits"
else
    echo "Warning: Could not validate key (HTTP $http_code). Saving anyway."
fi

# Store securely
if [[ "$(uname)" == "Darwin" ]]; then
    # macOS: use Keychain
    security delete-generic-password -s "$KEYCHAIN_SERVICE" 2>/dev/null || true
    security add-generic-password -s "$KEYCHAIN_SERVICE" -a "kie-ai" -w "$api_key"
    echo ""
    echo "API key stored in macOS Keychain (service: $KEYCHAIN_SERVICE)"
else
    # Linux/other: encrypted config file with restricted permissions
    mkdir -p "$KIE_CONFIG_DIR"
    chmod 700 "$KIE_CONFIG_DIR"
    echo "api_key=$api_key" > "$KIE_CONFIG_FILE"
    chmod 600 "$KIE_CONFIG_FILE"
    echo ""
    echo "API key stored in $KIE_CONFIG_FILE (permissions: 600)"
fi

echo ""
echo "Setup complete! The skill can now use your Kie.ai API."
