#!/bin/bash
# Update .web/env.json with API_URL from environment variable at runtime

set -e

API_URL="${API_URL:-http://localhost:8000}"

# Extract protocol, host, and port from API_URL
if [[ "$API_URL" =~ ^(https?://)([^:/]+)(:([0-9]+))? ]]; then
    PROTOCOL="${BASH_REMATCH[1]}"
    HOST="${BASH_REMATCH[2]}"
    PORT="${BASH_REMATCH[4]:-8000}"
    
    # Remove trailing slash
    API_URL="${API_URL%/}"
    
    # Update .web/env.json
    if [ -f "/app/.web/env.json" ]; then
        # Use Python to properly update JSON
        python3 <<EOF
import json
import os

api_url = os.environ.get('API_URL', 'http://localhost:8000')
api_url = api_url.rstrip('/')

# Determine protocol and host
if api_url.startswith('https://'):
    ws_protocol = 'wss://'
    http_protocol = 'https://'
elif api_url.startswith('http://'):
    ws_protocol = 'ws://'
    http_protocol = 'http://'
else:
    ws_protocol = 'ws://'
    http_protocol = 'http://'
    api_url = f'http://{api_url}'

# Remove protocol prefix for host extraction
host = api_url.replace('https://', '').replace('http://', '').split('/')[0]

# Read existing env.json
with open('/app/.web/env.json', 'r') as f:
    env_data = json.load(f)

# Update URLs
env_data['PING'] = f'{http_protocol}{host}/ping'
env_data['EVENT'] = f'{ws_protocol}{host}/_event'
env_data['UPLOAD'] = f'{http_protocol}{host}/_upload'
env_data['AUTH_CODESPACE'] = f'{http_protocol}{host}/auth-codespace'
env_data['HEALTH'] = f'{http_protocol}{host}/_health'
env_data['ALL_ROUTES'] = f'{http_protocol}{host}/_all_routes'

# Write back
with open('/app/.web/env.json', 'w') as f:
    json.dump(env_data, f)

print(f"Updated .web/env.json with API_URL: {api_url}")
EOF
    else
        echo "Warning: /app/.web/env.json not found"
    fi
else
    echo "Warning: Invalid API_URL format: $API_URL"
fi

# Execute the original command
exec "$@"

