#!/usr/bin/env bash
# log.sh - Logging utilities for homelab deployment

log() {
    local level=$1
    shift
    local message=$*
    echo "[$(date +'%Y-%m-%d %H:%M:%S')] [$level] $message"
}

# --- Load Events Library ---
if [[ -f "${LIB_PATH:-$(dirname "${BASH_SOURCE[0]}")}/events.sh" ]]; then
    source "${LIB_PATH:-$(dirname "${BASH_SOURCE[0]}")}/events.sh"
fi

# Structured log for machine reading
# timestamp, stage, host, service, command_result, info
struct_log() {
    local stage=$1
    local host=$2
    local service=$3
    local result=$4
    local info=$5
    log "STRUCT" "stage=$stage host=$host service=$service result=$result info=\"$info\""
    
    # Emit event if it matches normalized types
    local event_type=""
    local severity="info"
    
    case "$stage" in
        "deploy")
            if [[ "$result" == "success" ]]; then
                event_type="deployment_completed"
            elif [[ "$result" == "fail" ]]; then
                event_type="deployment_failed"
                severity="error"
            else
                event_type="deployment_started"
            fi
            ;;
        "validate")
            if [[ "$result" == "fail" ]]; then
                event_type="deployment_failed"
                severity="error"
            fi
            ;;
    esac
    
    if [[ -n "$event_type" ]] && command -v emit_event >/dev/null 2>&1; then
        emit_event "$event_type" "$severity" "deploy.sh" "$service" "${TIMESTAMP:-$(date +%s)}" "{\"stage\": \"$stage\", \"info\": \"$info\"}"
    fi
}

# export -f log
# export -f struct_log
