#!/bin/bash

# script/setup: Setup script used by DevContainers to prepare the project
#
# Installs optional development tools (pyright, GitHub Copilot CLI, git-cliff)
# and configures the environment. Called automatically by DevContainer postStartCommand.
#
# Usage:
#   ./script/setup/setup
#
# Examples:
#   ./script/setup/setup

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
cd "$SCRIPT_DIR/../.."

# shellcheck source=script/.lib/output.sh
source "$SCRIPT_DIR/../.lib/output.sh"

"$SCRIPT_DIR/bootstrap"

if [[ -z ${VIRTUAL_ENV:-} ]]; then
    log_header "Activating virtual environment"
    # shellcheck source=/dev/null
    source "$HOME/.local/ha-venv/bin/activate"
fi

if [[ ${HA_INSTALL_HACS:-"0"} == "1" ]]; then
    # Install HACS for testing with other custom components
    echo ""
    log_header "Installing HACS in dev environment"
    log_info "This allows testing your integration alongside other HACS components"

    # Ensure config directory is initialized by Home Assistant first
    if [[ ! -f config/.HA_VERSION ]]; then
        log_step "Initializing Home Assistant config directory"
        hass --config "${PWD}/config" --script ensure_config >/dev/null 2>&1 || true
    fi

    # Create custom_components directory if it doesn't exist
    mkdir -p config/custom_components

    # Clean up existing HACS installation if present
    if [[ -d config/custom_components/hacs ]]; then
        log_step "Removing existing HACS installation"
        rm -rf config/custom_components/hacs
    fi
    if [[ -L custom_components/hacs ]]; then
        log_step "Removing existing HACS symlink"
        rm -f custom_components/hacs
    fi

    # Download and extract HACS (stable release ZIP)
    cd config/custom_components
    log_step "Downloading HACS"
    if wget -q https://github.com/hacs/integration/releases/latest/download/hacs.zip && \
    unzip -q hacs.zip -d hacs && \
    rm hacs.zip; then
        cd ../..

        # Install HACS Python dependencies
        log_step "Installing HACS Python dependencies"
        if uv pip install -q 'aiogithubapi>=22.10.1'; then
            "$SCRIPT_DIR/sync-hacs"
            log_success "HACS installed successfully"
            log_info "Location: ${BOLD}config/custom_components/hacs/${NC}"
            log_info "Version: Stable release (no auto-updates)"
        else
            log_warning "Failed to install HACS Python dependencies"
            log_info "You can install manually: ${BOLD}uv pip install 'aiogithubapi>=22.10.1'${NC}"
        fi
    else
        log_warning "HACS installation failed"
        log_info "You can install manually:"
        log_step "${BOLD}cd config/custom_components${NC}"
        log_step "${BOLD}wget https://github.com/hacs/integration/releases/latest/download/hacs.zip${NC}"
        log_step "${BOLD}unzip hacs.zip -d hacs && rm hacs.zip${NC}"
        cd ../..
    fi
fi

echo ""
log_success "Project setup complete"
