#!/usr/bin/env bash
# syncro-env.sh — Resolve the repo root and the caller's Syncro API key from the SOPS vault.
#
# Source this instead of hardcoding a repo path or an API key:
#   source "$(dirname "${BASH_SOURCE[0]}")/syncro-env.sh"     # or by absolute path
#   curl -s "$SYNCRO_BASE/customers?api_key=$SYNCRO_API_KEY"
#
# Exports: CLAUDETOOLS_ROOT, VAULT_ROOT, SYNCRO_USER, SYNCRO_BASE, SYNCRO_API_KEY
#
# Root resolution mirrors vault.sh: derive from this script's own location, then let
# identity.json's claudetools_root override. Never hardcode a drive letter — the repo
# lives at C:/claudetools on some machines and D:/claudetools on others.
#
# Soft-fails like get-identity.sh: on any failure it warns, leaves SYNCRO_API_KEY empty,
# and returns 1 without exiting, so a sourcing skill degrades instead of dying.

_syncro_env_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
export CLAUDETOOLS_ROOT="$(cd "$_syncro_env_dir/../.." && pwd)"
_identity="$CLAUDETOOLS_ROOT/.claude/identity.json"

export SYNCRO_BASE="https://computerguru.syncromsp.com/api/v1"
export SYNCRO_API_KEY=""
export SYNCRO_USER=""
export VAULT_ROOT=""

if [ ! -f "$_identity" ]; then
    echo "[WARNING] identity.json not found at $_identity — Syncro calls will be unauthenticated" >&2
    return 1 2>/dev/null || exit 1
fi

# identity.json is authoritative for both the repo root and the vault location.
_root_override=$(jq -r '.claudetools_root // empty' "$_identity" 2>/dev/null)
[ -n "$_root_override" ] && [ -d "$_root_override" ] && export CLAUDETOOLS_ROOT="$_root_override"
export VAULT_ROOT=$(jq -r '.vault_path // empty' "$_identity" 2>/dev/null)
export SYNCRO_USER=$(jq -r '.user // empty' "$_identity" 2>/dev/null)

# Per-user token — attribution in Syncro depends on using the right one.
# Map a user name to their vaulted key path; empty = no key vaulted for them.
_syncro_key_path() {
    case "$1" in
        mike)   echo "msp-tools/syncro" ;;
        howard) echo "msp-tools/syncro-howard" ;;
        winter) echo "msp-tools/syncro-winter" ;;
        *)      echo "" ;;
    esac
}

# Prefer the requester's key when running on someone's behalf (e.g. the Discord
# bot sets CLAUDETOOLS_REQUESTER_USER per thread) so Syncro attributes actions
# to the person who asked. Fall back to the identity.json user when the
# requester has no vaulted key (e.g. rob) — never hard-fail on the preference.
_vault_path=""
_requester="${CLAUDETOOLS_REQUESTER_USER:-}"
if [ -n "$_requester" ] && [ "$_requester" != "$SYNCRO_USER" ]; then
    _req_path=$(_syncro_key_path "$_requester")
    if [ -n "$_req_path" ]; then
        _vault_path="$_req_path"
        export SYNCRO_USER="$_requester"
        echo "[INFO] Using Syncro key for requester '$_requester' (attribution)" >&2
    fi
fi
[ -z "$_vault_path" ] && _vault_path=$(_syncro_key_path "$SYNCRO_USER")

if [ -z "$_vault_path" ]; then
    echo "[WARNING] No Syncro key vaulted for user '$SYNCRO_USER' — enrichment skipped" >&2
    return 1 2>/dev/null || exit 1
fi

SYNCRO_API_KEY=$(bash "$CLAUDETOOLS_ROOT/.claude/scripts/vault.sh" \
    get-field "$_vault_path" credentials.credential 2>/dev/null | tail -1)
export SYNCRO_API_KEY

if [ -z "$SYNCRO_API_KEY" ]; then
    echo "[ERROR] Could not read $_vault_path from vault — is SOPS/age configured?" >&2
    bash "$CLAUDETOOLS_ROOT/.claude/scripts/log-skill-error.sh" "syncro-env" \
        "vault read failed for $_vault_path" --context "user=$SYNCRO_USER" >/dev/null 2>&1 || true
    return 1 2>/dev/null || exit 1
fi

unset _syncro_env_dir _identity _root_override _vault_path _requester _req_path
unset -f _syncro_key_path
return 0 2>/dev/null || true
