#!/bin/bash

set -e

# we're setting up claude code to work right after installation using our 
# api key that is present in .anthropic_key in this directory
# claude code cli doesn't make this simple, so this is kind of brittle

# Check if .anthropic_key file exists
if [ ! -f ".anthropic_key" ]; then
    echo "Error: .anthropic_key file not found in current directory"
    exit 1
fi

# Read the contents of the file and trim whitespace
KEY_CONTENT=$(cat ".anthropic_key" | tr -d '\n\r' | sed 's/^[[:space:]]*//;s/[[:space:]]*$//')

# Check if the contents are empty after trimming
if [ -z "$KEY_CONTENT" ]; then
    echo "Error: .anthropic_key file is empty or contains only whitespace" >&2
    exit 1
fi

LASTCHARS="${KEY_CONTENT: -20}"

# Check if the key value is at least 20 characters long
if [ ${#KEY_CONTENT} -lt 20 ]; then
    echo "Warning: Key value is shorter than 20 characters."
    exit 1
fi

# use the apiKeyHelper to avoid messing with envars that can be missed
claude config set --global theme dark
claude config set --global apiKeyHelper "$(pwd)/claude_api_key.sh"

# Check if settings.json file exists
if [ ! -f ~/.claude.json ]; then
    echo "Error: .claude.json file not found."
    exit 1
fi

jq --arg lastchars "$LASTCHARS" '.customApiKeyResponses = {
        "approved": [$lastchars],
        "rejected": []
    } | .hasCompletedOnboarding = true | .shiftEnterKeyBindingInstalled = true' ~/.claude.json > ~/.claude.json.tmp && mv ~/.claude.json.tmp ~/.claude.json


# lastly setup the local project settings to avoid these trust prompts
claude config set hasTrustDialogAccepted true
claude config set hasCompletedProjectOnboarding true

echo "Success, environment and project configuration complete."