#!/usr/bin/env bash
# Kie.ai API helper — handles auth, requests, polling, and downloads
set -euo pipefail

command -v python3 >/dev/null 2>&1 || { echo "ERROR: python3 required but not found." >&2; exit 1; }

# --- Retrieve API Key ---
get_api_key() {
    local key=""
    if [[ "$(uname)" == "Darwin" ]]; then
        key=$(security find-generic-password -s "kie-ai-api" -w 2>/dev/null || true)
    fi
    if [[ -z "$key" ]] && [[ -f "${HOME}/.config/kie-ai/config" ]]; then
        key=$(grep -oP 'api_key=\K.*' "${HOME}/.config/kie-ai/config" 2>/dev/null || true)
    fi
    if [[ -z "$key" ]]; then
        echo "ERROR: No Kie.ai API key found. Run setup_api_key.sh first." >&2
        exit 1
    fi
    echo "$key"
}

# --- Check Credits ---
check_credits() {
    local key
    key=$(get_api_key)
    curl -s -H "Authorization: Bearer $key" "https://api.kie.ai/api/v1/chat/credit"
}

# --- Create Task (Market unified endpoint) ---
# Usage: create_market_task '{"model":"nano-banana-2","input":{...}}'
create_market_task() {
    local key payload="$1"
    key=$(get_api_key)
    curl -s -X POST "https://api.kie.ai/api/v1/jobs/createTask" \
        -H "Authorization: Bearer $key" \
        -H "Content-Type: application/json" \
        -d "$payload"
}

# --- Create Task (Dedicated endpoint) ---
# Usage: create_dedicated_task "/api/v1/runway/generate" '{"prompt":"...","duration":5,...}'
create_dedicated_task() {
    local key endpoint="$1" payload="$2"
    key=$(get_api_key)
    curl -s -X POST "https://api.kie.ai${endpoint}" \
        -H "Authorization: Bearer $key" \
        -H "Content-Type: application/json" \
        -d "$payload"
}

# --- Poll Task Status (Market) ---
# Usage: poll_market_task "task_12345"
poll_market_task() {
    local key task_id="$1" max_attempts="${2:-60}" interval="${3:-10}"
    key=$(get_api_key)

    for ((i=1; i<=max_attempts; i++)); do
        local response
        response=$(curl -s -H "Authorization: Bearer $key" \
            "https://api.kie.ai/api/v1/jobs/recordInfo?taskId=${task_id}")

        local state
        state=$(echo "$response" | python3 -c "import sys,json; print(json.load(sys.stdin).get('data',{}).get('state','unknown'))" 2>/dev/null || echo "unknown")

        case "$state" in
            success)
                echo "$response"
                return 0
                ;;
            fail)
                echo "$response"
                return 1
                ;;
            waiting|queuing|generating)
                echo "[$i/$max_attempts] Status: $state — waiting ${interval}s..." >&2
                sleep "$interval"
                ;;
            *)
                echo "[$i/$max_attempts] Unknown state: $state — waiting ${interval}s..." >&2
                sleep "$interval"
                ;;
        esac
    done
    echo "ERROR: Timeout after $max_attempts attempts" >&2
    return 2
}

# --- Poll Task Status (Dedicated endpoint) ---
# Usage: poll_dedicated_task "/api/v1/veo/record-info" "task_12345"
poll_dedicated_task() {
    local key endpoint="$1" task_id="$2" max_attempts="${3:-60}" interval="${4:-10}"
    key=$(get_api_key)

    for ((i=1; i<=max_attempts; i++)); do
        local response
        response=$(curl -s -H "Authorization: Bearer $key" \
            "https://api.kie.ai${endpoint}?taskId=${task_id}")

        local flag
        flag=$(echo "$response" | python3 -c "import sys,json; print(json.load(sys.stdin).get('data',{}).get('successFlag',-1))" 2>/dev/null || echo "-1")

        case "$flag" in
            1)
                echo "$response"
                return 0
                ;;
            2|3)
                echo "$response"
                return 1
                ;;
            0)
                echo "[$i/$max_attempts] Generating — waiting ${interval}s..." >&2
                sleep "$interval"
                ;;
            *)
                echo "[$i/$max_attempts] Status flag: $flag — waiting ${interval}s..." >&2
                sleep "$interval"
                ;;
        esac
    done
    echo "ERROR: Timeout after $max_attempts attempts" >&2
    return 2
}

# --- Get Download URL ---
# Usage: get_download_url "https://tempfile..."
get_download_url() {
    local key url="$1"
    key=$(get_api_key)
    curl -s -X POST "https://api.kie.ai/api/v1/common/download-url" \
        -H "Authorization: Bearer $key" \
        -H "Content-Type: application/json" \
        -d "{\"url\":\"$url\"}"
}

# --- Download File ---
# Usage: download_file "https://tempfile..." "/path/to/output.png"
download_file() {
    local file_url="$1" output_path="$2"
    local download_response
    download_response=$(get_download_url "$file_url")

    local direct_url
    direct_url=$(echo "$download_response" | python3 -c "import sys,json; print(json.load(sys.stdin).get('data',''))" 2>/dev/null || echo "")

    if [[ -z "$direct_url" ]]; then
        # Fallback: try the original URL
        direct_url="$file_url"
    fi

    curl -sL -o "$output_path" "$direct_url"
    echo "Downloaded to: $output_path"
}

# --- Upload File (URL method) ---
# Usage: upload_file_url "https://example.com/image.png"
upload_file_url() {
    local key url="$1"
    key=$(get_api_key)
    curl -s -X POST "https://kieai.redpandaai.co/api/file-url-upload" \
        -H "Authorization: Bearer $key" \
        -H "Content-Type: application/json" \
        -d "{\"fileUrl\":\"$url\"}"
}

# --- Upload File (Stream method) ---
# Usage: upload_file_stream "/path/to/file.png"
upload_file_stream() {
    local key file_path="$1"
    local filename
    filename=$(basename "$file_path")
    key=$(get_api_key)
    curl -s -X POST "https://kieai.redpandaai.co/api/file-stream-upload" \
        -H "Authorization: Bearer $key" \
        -F "file=@${file_path}" \
        -F "uploadPath=${filename}"
}

# --- Main dispatcher ---
case "${1:-help}" in
    credits)        check_credits ;;
    create-market)  create_market_task "$2" ;;
    create)         create_dedicated_task "$2" "$3" ;;
    poll-market)    poll_market_task "$2" "${3:-60}" "${4:-10}" ;;
    poll)           poll_dedicated_task "$2" "$3" "${4:-60}" "${5:-10}" ;;
    download-url)   get_download_url "$2" ;;
    download)       download_file "$2" "$3" ;;
    upload-url)     upload_file_url "$2" ;;
    upload-stream)  upload_file_stream "$2" ;;
    help)
        echo "Usage: kie_api.sh <command> [args]"
        echo ""
        echo "Commands:"
        echo "  credits                          Check remaining credits"
        echo "  create-market '<json>'           Create task (Market unified)"
        echo "  create '<endpoint>' '<json>'     Create task (dedicated endpoint)"
        echo "  poll-market <taskId> [max] [sec] Poll Market task status"
        echo "  poll <endpoint> <taskId> [max]   Poll dedicated task status"
        echo "  download-url <url>               Get direct download URL"
        echo "  download <url> <output_path>     Download generated file"
        echo "  upload-url <url>                 Upload file by URL"
        echo "  upload-stream <file_path>        Upload local file"
        ;;
    *)
        echo "Unknown command: $1. Use 'help' for usage." >&2
        exit 1
        ;;
esac
