#!/usr/bin/env bash
# Activate Deep Research environment (venv + secrets)
# Usage: cd <project-root> && source scripts/activate.sh

if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
    echo "ERROR: use 'source', not 'bash':"
    echo "  source scripts/activate.sh"
    exit 1
fi

# Project root = directory containing pyproject.toml
# Walk up from $PWD until we find it (or give up at /)
_find_root() {
    local dir="${PWD}"
    while [[ "${dir}" != "/" ]]; do
        [[ -f "${dir}/pyproject.toml" ]] && echo "${dir}" && return 0
        dir="$(dirname "${dir}")"
    done
    return 1
}

_DR_ROOT="$(_find_root 2>/dev/null)"
if [[ -z "${_DR_ROOT}" ]]; then
    echo "ERROR: pyproject.toml not found in ${PWD} or any parent."
    echo "  cd to the project root first, then: source scripts/activate.sh"
    return 1
fi

# activate venv
if [[ -f "${_DR_ROOT}/.venv/bin/activate" ]]; then
    source "${_DR_ROOT}/.venv/bin/activate"
    echo "venv: active ($(python --version 2>&1))"
else
    echo "venv: not found - run: bash ${_DR_ROOT}/scripts/setup.sh"
fi

# load secrets
if [[ -f "${_DR_ROOT}/secrets.env" ]]; then
    set -a
    source "${_DR_ROOT}/secrets.env"
    set +a
    if [[ -n "${ZENMUX_API_KEY:-}" ]]; then
        echo "secrets: loaded (ZENMUX_API_KEY=${ZENMUX_API_KEY:0:12}...)"
    else
        echo "secrets: loaded but ZENMUX_API_KEY is empty"
    fi
else
    echo "secrets: missing - run: cp secrets.env.example secrets.env"
fi

# npm proxy fix: unset empty npm_config_proxy so npm inherits system http_proxy
# without this, opencode crashes with "proxy.url must be a non-empty string"
# when dynamically loading npm packages like @ai-sdk/anthropic
if [[ -z "${npm_config_proxy:-}" ]]; then
    unset npm_config_proxy
fi
if [[ -z "${npm_config_https_proxy:-}" ]]; then
    unset npm_config_https_proxy
fi

unset -f _find_root
unset _DR_ROOT
