#!/bin/bash
# =============================================================================
#  dig-PT-claude.sh
#  Claude Code Installation & Configuration Script (macOS)
# -----------------------------------------------------------------------------
#  Description : Installs Claude Code via Homebrew and writes the PwC-tuned
#                ~/.claude/settings.json (gateway base URL, auth token built
#                from API key + tenant ID, OTel exporter, model defaults
#                pulled from the gateway's /models endpoint with embedded
#                fallbacks).
#
#  Author      : S. Cannilla
#  Copyright   : (c) 2026 S. Cannilla - Free to use, modify and redistribute.
#                Provided "as is", without warranty of any kind.
#  License     : Public Domain / Free to use
#  Last Update : 2026-05-28
#  Version     : 1.0.0
#
#  Platform    : macOS (Darwin) - Apple Silicon and Intel
#  Shell       : bash / zsh
#  Requires    : macOS, Homebrew, internet access
#
#  Usage       : chmod +x dig-PT-claude.sh && ./dig-PT-claude.sh
#
#  Notes       : - Designed for use behind the PwC corporate gateway.
#                - Idempotent: re-running skips work already done.
#                - Inline tags "#SC:" mark intentional design decisions.
# =============================================================================

set -o pipefail

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# Helper functions
print_header() {
    echo ""
    echo -e "${BLUE}========================================${NC}"
    echo -e "${BLUE}$1${NC}"
    echo -e "${BLUE}========================================${NC}"
    echo ""
}

print_success() {
    echo -e "${GREEN}✓ $1${NC}"
}

print_warning() {
    echo -e "${YELLOW}⚠ $1${NC}"
}

print_error() {
    echo -e "${RED}✗ $1${NC}"
}

ask_yes_no() {
    local prompt="$1"
    local default="${2:-y}"
    local answer

    if [[ "$default" == "y" ]]; then
        prompt="$prompt [Y/n]: "
    else
        prompt="$prompt [y/N]: "
    fi

    read -p "$prompt" answer
    answer=${answer:-$default}

    [[ "$answer" =~ ^[Yy]$ ]]
}

#SC: Best-effort GET to the PwC gateway /models endpoint. Prints lines like
#SC: "OPUS=<id>" for each entry whose `suggested` field is OPUS/SONNET/HAIKU
#SC: and whose `id` is non-empty. Any failure (curl error, missing python3,
#SC: malformed JSON) prints nothing to stdout and a single warning to stderr;
#SC: callers fall back to embedded model defaults.
fetch_suggested_models() {
    local endpoint="https://idi-coding-agents.pwc.it/models"
    local body
    if ! command -v python3 >/dev/null 2>&1; then
        print_warning "python3 not found - using template model defaults" >&2
        return 0
    fi
    body=$(curl --fail --silent --show-error --max-time 15 \
        -H 'Accept: application/json' "$endpoint" 2>/dev/null) || {
        print_warning "Could not fetch ${endpoint} - using template model defaults" >&2
        return 0
    }
    echo "$body" | python3 -c '
import json, sys
try:
    data = json.loads(sys.stdin.read()).get("data") or []
except Exception:
    sys.exit(1)
allowed = {"OPUS", "SONNET", "HAIKU"}
for item in data:
    tier = str(item.get("suggested") or "").upper()
    mid  = str(item.get("id") or "")
    if tier in allowed and mid:
        print(f"{tier}={mid}")
' 2>/dev/null || print_warning "Malformed /models response - using template model defaults" >&2
}

#SC: Homebrew prefix detected once, reused by every brew-dependent step. Empty until detect_brew succeeds.
BREW_PREFIX=""

#SC: Locate brew on Apple Silicon (/opt/homebrew) or Intel (/usr/local). Sources shellenv so PATH is set for this script too.
detect_brew() {
    if [ -n "$BREW_PREFIX" ] && [ -x "$BREW_PREFIX/bin/brew" ]; then
        return 0
    fi
    if command -v brew &>/dev/null; then
        BREW_PREFIX="$(brew --prefix 2>/dev/null)"
        [ -n "$BREW_PREFIX" ] && return 0
    fi
    if [ -x "/opt/homebrew/bin/brew" ]; then
        eval "$(/opt/homebrew/bin/brew shellenv)"
        BREW_PREFIX="/opt/homebrew"
        return 0
    fi
    if [ -x "/usr/local/bin/brew" ]; then
        eval "$(/usr/local/bin/brew shellenv)"
        BREW_PREFIX="/usr/local"
        return 0
    fi
    return 1
}

#SC: Guard for steps that call brew. Returns non-zero so caller can skip gracefully.
require_brew() {
    if detect_brew; then
        return 0
    fi
    print_error "Homebrew is not installed. Install Homebrew first, then rerun this script."
    return 1
}

# Check if running on macOS
if [[ "$(uname)" != "Darwin" ]]; then
    print_error "This script is designed for macOS only."
    exit 1
fi

# ASCII Art Banner
echo ""
echo -e "${BLUE}"
cat << 'BANNER'
 ____  ___ ____   ____   ___  _____
|  _ \|_ _/ ___| |  _ \ ( _ )|_   _|
| | | || | |  _  | |_) |/ _ \ | |
| |_| || | |_| | |  __/| (_) || |
|____/|___\____| |_|    \___/ |_|
            Claude Code installer
BANNER
echo -e "${NC}"
echo ""

print_header "Claude Code Installation & Configuration"

if ask_yes_no "Install and configure Claude Code?"; then
    if command -v claude &>/dev/null; then
        print_success "Claude Code already installed"
    else
        #SC: Two supported install paths - brew cask vs. Anthropic's curl|bash installer.
        #SC: Loop until the user picks a valid option; default to brew on empty input.
        echo ""
        echo "Choose installation method:"
        echo "  1) Homebrew (brew install claude-code)"
        echo "  2) Official installer (curl -fsSL https://claude.ai/install.sh | bash)"
        echo ""

        INSTALL_METHOD=""
        while true; do
            read -p "Enter your choice (1-2) [1]: " INSTALL_CHOICE
            INSTALL_CHOICE=${INSTALL_CHOICE:-1}
            case "$INSTALL_CHOICE" in
                1) INSTALL_METHOD="brew";     break ;;
                2) INSTALL_METHOD="official"; break ;;
                *) echo "Invalid choice. Please enter 1 or 2." ;;
            esac
        done

        if [[ "$INSTALL_METHOD" == "brew" ]]; then
            if ! require_brew; then
                print_warning "Cannot install Claude Code without Homebrew. Skipping install step; continuing with settings configuration."
            else
                echo "Installing Claude Code via Homebrew..."
                brew install claude-code
                print_success "Claude Code installed"
            fi
        else
            echo "Installing Claude Code via the official installer..."
            if curl -fsSL https://claude.ai/install.sh | bash; then
                print_success "Claude Code installed"
                #SC: Official installer drops the binary under ~/.local/bin (or similar).
                #SC: Surface a hint if it is not yet on PATH for the current shell.
                command -v claude &>/dev/null || \
                    print_warning "'claude' not on PATH yet - open a new terminal or update PATH (e.g. export PATH=\"\$HOME/.local/bin:\$PATH\")."
            else
                print_error "Official installer failed. Skipping install step; continuing with settings configuration."
            fi
        fi
    fi

    # Prompt for API key and tenant ID
    echo ""
    echo "Please enter your Claude Code credentials:"
    echo ""

    read -p "Enter your API Key: " CLAUDE_API_KEY
    read -p "Enter your Tenant ID: " CLAUDE_TENANT_ID
    read -p "Enter your PwC email (name.surname@pwc.com): " CLAUDE_EMAIL

    if [[ -n "$CLAUDE_API_KEY" && -n "$CLAUDE_TENANT_ID" ]]; then
        # Create .claude directory
        mkdir -p "$HOME/.claude"

        #SC: Embedded defaults match install-claude.ps1; overwritten below if /models has a suggestion.
        OPUS_MODEL="claude-opus-4-7"
        SONNET_MODEL="claude-sonnet-4-6"
        HAIKU_MODEL="claude-haiku-4-5-20251001"
        OPUS_SOURCE="template (fallback)"
        SONNET_SOURCE="template (fallback)"
        HAIKU_SOURCE="template (fallback)"

        #SC: temp file instead of <(...) process substitution so the script
        #SC: parses cleanly under sh / bash POSIX mode as well as bash.
        _models_tmp=$(mktemp -t pt-models.XXXXXX)
        fetch_suggested_models > "$_models_tmp"
        while IFS='=' read -r tier id; do
            case "$tier" in
                OPUS)   OPUS_MODEL="$id";   OPUS_SOURCE="/models (suggested)" ;;
                SONNET) SONNET_MODEL="$id"; SONNET_SOURCE="/models (suggested)" ;;
                HAIKU)  HAIKU_MODEL="$id";  HAIKU_SOURCE="/models (suggested)" ;;
            esac
        done < "$_models_tmp"
        rm -f "$_models_tmp"

        # Create settings.json
        cat > "$HOME/.claude/settings.json" << EOF
{
  "env": {
    "ANTHROPIC_BASE_URL": "https://idi-coding-agents.pwc.it",
    "ANTHROPIC_AUTH_TOKEN": "apikey=${CLAUDE_API_KEY}&tenantid=${CLAUDE_TENANT_ID}",
    "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC": "1",
    "CLAUDE_CODE_SKIP_AUTH_LOGIN": "1",
    "CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS": "1",
    "CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS": "1",
    "CLAUDE_CODE_DISABLE_AUTO_MEMORY": "0",
    "CLAUDE_CODE_ENABLE_TELEMETRY": "1",
    "ANTHROPIC_DEFAULT_HAIKU_MODEL": "${HAIKU_MODEL}",
    "ANTHROPIC_DEFAULT_SONNET_MODEL": "${SONNET_MODEL}",
    "ANTHROPIC_DEFAULT_OPUS_MODEL": "${OPUS_MODEL}",
    "OTEL_METRICS_EXPORTER": "otlp",
    "OTEL_LOGS_EXPORTER": "otlp",
    "OTEL_EXPORTER_OTLP_PROTOCOL": "http/protobuf",
    "OTEL_EXPORTER_OTLP_ENDPOINT": "https://idi-coding-agents.pwc.it",
    "OTEL_EXPORTER_OTLP_HEADERS": "authorization=Bearer apikey=${CLAUDE_API_KEY}&tenantid=${CLAUDE_TENANT_ID}",
    "OTEL_RESOURCE_ATTRIBUTES": "user.email=${CLAUDE_EMAIL}"
  },
  "attribution": {
    "commit": "Co-Authored-By: PwC SDLC Claude Code",
    "pr": "Co-Authored-By: PwC SDLC Claude Code"
  },
  "model": "sonnet[1m]",
  "extraKnownMarketplaces": {
    "anthropic-agent-skills": {
      "source": {
        "source": "github",
        "repo": "anthropics/skills"
      }
    }
  },
  "effortLevel": "medium"
}
EOF
        print_success "Claude Code settings saved to ~/.claude/settings.json"
        echo "  ANTHROPIC_DEFAULT_OPUS_MODEL   = ${OPUS_MODEL}   [${OPUS_SOURCE}]"
        echo "  ANTHROPIC_DEFAULT_SONNET_MODEL = ${SONNET_MODEL} [${SONNET_SOURCE}]"
        echo "  ANTHROPIC_DEFAULT_HAIKU_MODEL  = ${HAIKU_MODEL}  [${HAIKU_SOURCE}]"
    else
        print_warning "API Key or Tenant ID not provided. Skipping configuration."
        print_warning "You can manually configure Claude Code later by creating ~/.claude/settings.json"
    fi
fi

# ============================================
# Final Summary
# ============================================
print_header "Setup Complete!"

command -v claude &>/dev/null && print_success "Claude Code" || print_warning "Claude Code not on PATH (open a new terminal or run 'source ~/.zshrc')"
[ -f "$HOME/.claude/settings.json" ] && print_success "~/.claude/settings.json present"

echo ""
print_warning "Please restart your terminal or run 'source ~/.zshrc' to apply all changes."
echo ""
echo "To verify your installation, run these commands in a new terminal:"
echo "  claude --version"
echo "  claude doctor"
echo ""

print_success "Setup script completed!"
