#!/bin/bash
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0

# Schema-driven validation for generated deploy payloads.
# Validates configuration against AWS service models before deployment.
#
# Usage:
#   ./do/validate [--format json] [--smart]
#
# Exit codes:
#   0 - Validation passed (no errors)
#   1 - Validation failed (errors found)
#   2 - Validation could not run (registry missing)

set -e
set -u
set -o pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_DIR="$(cd "${SCRIPT_DIR}/.." && pwd)"

# Parse flags
FORMAT="text"
SMART=""
for arg in "$@"; do
    case "$arg" in
        --format=json|--format=JSON) FORMAT="json" ;;
        --smart) SMART="--smart" ;;
        --help|-h)
            echo "Usage: ./do/validate [--format json] [--smart]"
            echo ""
            echo "Options:"
            echo "  --format=json  Output validation report as JSON"
            echo "  --smart        Enable smart-mode validators (requires MCP config)"
            echo ""
            echo "Exit codes:"
            echo "  0 - Validation passed"
            echo "  1 - Validation failed (errors found)"
            echo "  2 - Validation could not run"
            exit 0
            ;;
    esac
done

echo "🔍 Running schema validation..."

# Invoke the Node.js validation runner
exec node -e "
import('${PROJECT_DIR}/node_modules/@aws/ml-container-creator/src/lib/validate-runner.js')
    .then(m => m.run({ configDir: '${SCRIPT_DIR}', format: '${FORMAT}', smart: ${SMART:+true}${SMART:-false} }))
    .catch(() => {
        // Fallback: try local path for development
        import('${PROJECT_DIR}/src/lib/validate-runner.js')
            .then(m => m.run({ configDir: '${SCRIPT_DIR}', format: '${FORMAT}', smart: ${SMART:+true}${SMART:-false} }))
            .catch(e => { console.error('Failed to load validator:', e.message); process.exit(2); });
    });
" 2>/dev/null || node --input-type=module -e "
import { run } from '${PROJECT_DIR}/src/lib/validate-runner.js';
run({ configDir: '${SCRIPT_DIR}', format: '${FORMAT}', smart: ${SMART:+true}${SMART:-false} });
"
