#!/usr/bin/env bash
# Generate Standard JSON Input from source project for Etherscan verification
# Usage: ./generate-standard-json-from-source.sh

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
SOURCE_PROJECT="/home/intlc/projects/smom-dbis-138"
OUTPUT_FILE="$PROJECT_ROOT/docs/CCIPWETH9Bridge_standard_json_generated.json"

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
NC='\033[0m'

log_info() { echo -e "${BLUE}[INFO]${NC} $1"; }
log_success() { echo -e "${GREEN}[✓]${NC} $1"; }
log_warn() { echo -e "${YELLOW}[⚠]${NC} $1"; }
log_error() { echo -e "${RED}[✗]${NC} $1"; }
log_step() { echo -e "${CYAN}[STEP]${NC} $1"; }

log_info "========================================="
log_info "Generate Standard JSON from Source"
log_info "========================================="
log_info ""

# Check prerequisites
if [ ! -d "$SOURCE_PROJECT" ]; then
    log_error "Source project not found: $SOURCE_PROJECT"
    exit 1
fi

if ! command -v forge &> /dev/null; then
    log_error "forge command not found. Please install Foundry."
    exit 1
fi

cd "$SOURCE_PROJECT"

# Step 1: Clean build
log_step "Step 1: Cleaning previous build..."
forge clean 2>/dev/null || true
log_success "Build cleaned"

# Step 2: Build with exact deployment settings
log_step "Step 2: Building contract with deployment settings..."
log_info "Settings: --via-ir --optimize --optimizer-runs 200"

# Try to install dependencies first
log_info "Installing dependencies..."
if forge install 2>/dev/null; then
    log_success "Dependencies installed"
else
    log_warn "Dependency installation had issues, continuing anyway..."
fi

# Build only the specific contract file to avoid script compilation errors
log_info "Building CCIPWETH9Bridge contract..."
if forge build --via-ir --optimize --optimizer-runs 200 --force --skip script/ 2>&1 | tee /tmp/forge-build.log; then
    log_success "Build successful"
else
    log_warn "Full project build failed, trying contract-only approach..."
    # If full build fails, we'll use the flattened source we already have
    log_info "Will use existing flattened source instead"
fi

# Step 3: Try to extract Standard JSON from build artifacts (if build succeeded)
BUILD_ARTIFACT="$SOURCE_PROJECT/out/CCIPWETH9Bridge.sol/CCIPWETH9Bridge.json"

if [ -f "$BUILD_ARTIFACT" ]; then
    log_step "Step 3: Extracting Standard JSON from build artifacts..."
    log_info "Found build artifact: $BUILD_ARTIFACT"
    
    # Try to extract Standard JSON from metadata if available
    if command -v jq &> /dev/null; then
        if jq -e '.metadata' "$BUILD_ARTIFACT" > /dev/null 2>&1; then
            log_info "Attempting to extract Standard JSON from metadata..."
            # Note: Metadata is base64 encoded, would need decoding
            log_info "Using flattened source approach instead"
        fi
    fi
else
    log_info "Build artifacts not available, using flattened source"
fi

# Step 4: Use existing flattened source (already includes all dependencies)
log_step "Step 4: Using existing flattened source..."

FLATTENED_FILE="$PROJECT_ROOT/docs/CCIPWETH9Bridge_flattened.sol"

if [ ! -f "$FLATTENED_FILE" ]; then
    log_warn "Flattened file not found, will create from source..."
    
    # Check if we can use the source file
    SOURCE_FILE="$SOURCE_PROJECT/contracts/ccip/CCIPWETH9Bridge.sol"
    IRouterClient_FILE="$SOURCE_PROJECT/contracts/ccip/IRouterClient.sol"
    
    if [ ! -f "$SOURCE_FILE" ]; then
        log_error "Source file not found: $SOURCE_FILE"
        exit 1
    fi
    
    # Read source content and include IRouterClient if needed
    log_info "Reading source files..."
    if [ -f "$IRouterClient_FILE" ]; then
        # Combine IRouterClient and CCIPWETH9Bridge
        SOURCE_CONTENT=$(cat "$IRouterClient_FILE" && echo "" && cat "$SOURCE_FILE")
    else
        SOURCE_CONTENT=$(cat "$SOURCE_FILE")
    fi
else
    log_info "Using existing flattened file: $FLATTENED_FILE"
    SOURCE_CONTENT=$(cat "$FLATTENED_FILE")
fi

# Create Standard JSON structure
log_info "Creating Standard JSON structure..."

if ! command -v jq &> /dev/null; then
    log_error "jq is required for JSON encoding. Please install jq."
    exit 1
fi

cat > "$OUTPUT_FILE" <<EOF
{
  "language": "Solidity",
  "sources": {
    "CCIPWETH9Bridge.sol": {
      "content": $(echo "$SOURCE_CONTENT" | jq -Rs .)
    }
  },
  "settings": {
    "optimizer": {
      "enabled": true,
      "runs": 200
    },
    "viaIR": true,
    "evmVersion": "london",
    "outputSelection": {
      "*": {
        "*": [
          "abi",
          "evm.bytecode",
          "evm.deployedBytecode",
          "evm.bytecode.sourceMap",
          "evm.deployedBytecode.sourceMap"
        ]
      }
    }
  }
}
EOF

if [ -f "$OUTPUT_FILE" ]; then
    log_success "Standard JSON generated: $OUTPUT_FILE"
    
    # Validate JSON
    if command -v jq &> /dev/null; then
        if jq empty "$OUTPUT_FILE" 2>/dev/null; then
            log_success "JSON is valid"
        else
            log_error "Generated JSON is invalid"
            exit 1
        fi
    fi
    
    log_info ""
    log_info "File size: $(du -h "$OUTPUT_FILE" | cut -f1)"
    log_info ""
    log_success "Standard JSON ready for Etherscan verification!"
    log_info ""
    log_info "Next steps:"
    log_info "1. Review the generated file: $OUTPUT_FILE"
    log_info "2. Use it for Etherscan verification"
    log_info "3. Select compiler version: v0.8.20+commit.a1b79de6"
    log_info "4. Enable 'Via IR' option"
else
    log_error "Failed to generate Standard JSON"
    exit 1
fi

