#!/bin/bash
# Grid Environment Variable Support
# These override .grid/config.json settings
#
# Usage:
#   source this file, or set variables before running Claude Code
#
# Priority (highest first):
#   1. GRID_* environment variables
#   2. CLAUDE_CODE_SUBAGENT_MODEL
#   3. .claude/settings.local.json
#   4. .claude/settings.json
#   5. ~/.claude/settings.json
#   6. .grid/config.json (legacy)

# =============================================================================
# GRID ENVIRONMENT VARIABLES
# =============================================================================

# Model tier: quality (opus), balanced (sonnet), budget (haiku)
# Default: quality
GRID_MODEL_TIER="${GRID_MODEL_TIER:-quality}"

# Budget limit in dollars (0 = unlimited)
# Default: 0 (unlimited)
GRID_BUDGET_LIMIT="${GRID_BUDGET_LIMIT:-0}"

# Auto-verify with Recognizer after execution
# Default: true
GRID_AUTO_VERIFY="${GRID_AUTO_VERIFY:-true}"

# Auto-run refinement swarm after execution
# Default: false
GRID_AUTO_REFINE="${GRID_AUTO_REFINE:-false}"

# Daemon/background mode
# Default: false
GRID_DAEMON_MODE="${GRID_DAEMON_MODE:-false}"

# =============================================================================
# EXPORT FOR SUBPROCESSES
# =============================================================================

export GRID_MODEL_TIER
export GRID_BUDGET_LIMIT
export GRID_AUTO_VERIFY
export GRID_AUTO_REFINE
export GRID_DAEMON_MODE

# =============================================================================
# HELPER FUNCTIONS
# =============================================================================

# Get effective config value (env overrides file)
# Usage: grid_get_config <key>
# Example: grid_get_config model_tier
grid_get_config() {
    local key="$1"
    local file_value=""

    # Try to read from .grid/config.json
    if [[ -f ".grid/config.json" ]]; then
        file_value=$(jq -r ".$key // empty" .grid/config.json 2>/dev/null)
    fi

    # Environment variable takes precedence
    case "$key" in
        model_tier)
            echo "${GRID_MODEL_TIER:-${file_value:-quality}}"
            ;;
        budget_limit)
            echo "${GRID_BUDGET_LIMIT:-${file_value:-0}}"
            ;;
        auto_verify)
            echo "${GRID_AUTO_VERIFY:-${file_value:-true}}"
            ;;
        auto_refine)
            echo "${GRID_AUTO_REFINE:-${file_value:-false}}"
            ;;
        daemon_mode)
            echo "${GRID_DAEMON_MODE:-${file_value:-false}}"
            ;;
        *)
            # For other keys, just return file value
            echo "$file_value"
            ;;
    esac
}

# Check if a boolean config is enabled
# Usage: grid_is_enabled <key>
# Returns: 0 if true/enabled, 1 if false/disabled
grid_is_enabled() {
    local value
    value=$(grid_get_config "$1")

    case "$value" in
        true|True|TRUE|yes|Yes|YES|1|on|On|ON)
            return 0
            ;;
        *)
            return 1
            ;;
    esac
}

# Get model for a specific agent based on tier
# Usage: grid_get_model <agent_type>
# Example: grid_get_model planner
grid_get_model() {
    local agent_type="$1"
    local tier
    tier=$(grid_get_config "model_tier")

    # Check for Claude Code's native subagent model override first
    if [[ -n "$CLAUDE_CODE_SUBAGENT_MODEL" ]]; then
        echo "$CLAUDE_CODE_SUBAGENT_MODEL"
        return
    fi

    # Check for custom per-agent model in config
    if [[ -f ".grid/config.json" ]]; then
        local custom_model
        custom_model=$(jq -r ".models.$agent_type // empty" .grid/config.json 2>/dev/null)
        if [[ -n "$custom_model" ]]; then
            echo "$custom_model"
            return
        fi
    fi

    # Fall back to tier-based model selection
    case "$tier" in
        quality)
            echo "opus"
            ;;
        balanced)
            echo "sonnet"
            ;;
        budget)
            case "$agent_type" in
                planner|executor|persona_simulator|refinement_synth)
                    # These need reasoning capability
                    echo "sonnet"
                    ;;
                recognizer|visual_inspector|e2e_exerciser|scout|accountant|guard)
                    # These can use cheaper model
                    echo "haiku"
                    ;;
                *)
                    echo "sonnet"
                    ;;
            esac
            ;;
        *)
            # Default to quality tier
            echo "opus"
            ;;
    esac
}

# Display current configuration
# Usage: grid_show_config
grid_show_config() {
    echo "GRID ENVIRONMENT CONFIGURATION"
    echo "==============================="
    echo ""
    echo "Environment Variables:"
    echo "  GRID_MODEL_TIER:    ${GRID_MODEL_TIER:-<not set>}"
    echo "  GRID_BUDGET_LIMIT:  ${GRID_BUDGET_LIMIT:-<not set>}"
    echo "  GRID_AUTO_VERIFY:   ${GRID_AUTO_VERIFY:-<not set>}"
    echo "  GRID_AUTO_REFINE:   ${GRID_AUTO_REFINE:-<not set>}"
    echo "  GRID_DAEMON_MODE:   ${GRID_DAEMON_MODE:-<not set>}"
    echo ""
    echo "Claude Code Variables:"
    echo "  CLAUDE_CODE_SUBAGENT_MODEL: ${CLAUDE_CODE_SUBAGENT_MODEL:-<not set>}"
    echo ""
    echo "Effective Configuration:"
    echo "  Model Tier:    $(grid_get_config model_tier)"
    echo "  Budget Limit:  $(grid_get_config budget_limit)"
    echo "  Auto-Verify:   $(grid_get_config auto_verify)"
    echo "  Auto-Refine:   $(grid_get_config auto_refine)"
    echo "  Daemon Mode:   $(grid_get_config daemon_mode)"
    echo ""
}

# =============================================================================
# VALIDATION
# =============================================================================

# Validate model tier value
grid_validate_tier() {
    local tier="$1"
    case "$tier" in
        quality|balanced|budget|custom)
            return 0
            ;;
        *)
            echo "Invalid model tier: $tier" >&2
            echo "Valid options: quality, balanced, budget, custom" >&2
            return 1
            ;;
    esac
}

# Validate budget limit value
grid_validate_budget() {
    local budget="$1"
    if [[ "$budget" =~ ^[0-9]+(\.[0-9]+)?$ ]]; then
        return 0
    else
        echo "Invalid budget limit: $budget" >&2
        echo "Must be a number (e.g., 10, 50.00)" >&2
        return 1
    fi
}
