#!/usr/bin/env bash
# Complete Fix for Oracle Publisher Service
# Fixes all issues: transaction signing, parsers, API keys, authorization
# Usage: ./scripts/fix-oracle-publisher-complete.sh

set -euo pipefail

PROXMOX_HOST="${PROXMOX_HOST:-192.168.11.10}"
VMID=3500

# 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}[WARN]${NC} $1"; }
log_error() { echo -e "${RED}[ERROR]${NC} $1"; }
log_detail() { echo -e "${CYAN}[DETAIL]${NC} $1"; }

echo "========================================="
echo "Complete Oracle Publisher Fix"
echo "========================================="
echo ""

# Fix 1: Transaction signing
log_info "Fix 1: Transaction signing (rawTransaction -> raw_transaction)..."
ssh "root@$PROXMOX_HOST" "pct exec $VMID -- bash" << 'EOF'
cd /opt/oracle-publisher
sed -i 's/\.rawTransaction/.raw_transaction/g' oracle_publisher.py
chown oracle:oracle oracle_publisher.py
echo "✓ Fixed"
EOF
log_success "Transaction signing fixed"

# Fix 2: Parser configuration
log_info "Fix 2: Price parser configuration..."
ssh "root@$PROXMOX_HOST" "pct exec $VMID -- bash" << 'EOF'
cd /opt/oracle-publisher
sed -i 's|DATA_SOURCE_1_PARSER=coingecko|DATA_SOURCE_1_PARSER=ethereum.usd|' .env
sed -i 's|DATA_SOURCE_2_PARSER=binance|DATA_SOURCE_2_PARSER=USD|' .env
echo "✓ Fixed"
EOF
log_success "Parser configuration fixed"

# Fix 3: Improve price parser in Python
log_info "Fix 3: Improving price parser logic..."
ssh "root@$PROXMOX_HOST" "pct exec $VMID -- bash" << 'PYEOF'
cd /opt/oracle-publisher
python3 << 'PYFIX'
with open('oracle_publisher.py', 'r') as f:
    content = f.read()

# Improve _parse_price method
old_method = '''    def _parse_price(self, data: dict, parser: str) -> Optional[str]:
        """Parse price from JSON data"""
        # Simple implementation - can be enhanced with jsonpath
        try:
            keys = parser.split('.')
            value = data
            for key in keys:
                value = value[key]
            return str(value)
        except (KeyError, TypeError):
            return None'''

new_method = '''    def _parse_price(self, data: dict, parser: str) -> Optional[str]:
        """Parse price from JSON data"""
        # Handle different API response formats
        try:
            # If parser is a simple key (like 'USD'), try direct access
            if parser in data:
                return str(data[parser])
            
            # Otherwise, try dot-notation path
            keys = parser.split('.')
            value = data
            for key in keys:
                if isinstance(value, dict):
                    value = value[key]
                else:
                    return None
            return str(value)
        except (KeyError, TypeError, AttributeError):
            # Try to find price in common locations
            for key in ['price', 'usd', 'USD', 'ethereum', 'ETH']:
                if key in data:
                    if isinstance(data[key], dict) and 'usd' in data[key]:
                        return str(data[key]['usd'])
                    elif isinstance(data[key], (int, float, str)):
                        return str(data[key])
            return None'''

if old_method in content:
    content = content.replace(old_method, new_method)
    with open('oracle_publisher.py', 'w') as f:
        f.write(content)
    print('✓ Improved')
else:
    print('Already updated')

PYFIX
chown oracle:oracle oracle_publisher.py
venv/bin/python -m py_compile oracle_publisher.py && echo "✓ Syntax valid" || echo "✗ Syntax error"
PYEOF
log_success "Price parser improved"

# Fix 4: Update data sources
log_info "Fix 4: Updating data sources (remove Binance, use CryptoCompare)..."
ssh "root@$PROXMOX_HOST" "pct exec $VMID -- bash" << 'EOF'
cd /opt/oracle-publisher
# Update CryptoCompare URL if not already set
if ! grep -q 'cryptocompare.com' .env; then
    sed -i 's|DATA_SOURCE_2_URL=.*|DATA_SOURCE_2_URL=https://min-api.cryptocompare.com/data/price?fsym=ETH\&tsyms=USD|' .env
fi
echo "✓ Updated"
EOF
log_success "Data sources updated"

# Restart service
log_info "Restarting service..."
ssh "root@$PROXMOX_HOST" "pct exec $VMID -- systemctl restart oracle-publisher"
sleep 5
log_success "Service restarted"

# Verify
log_info "Verifying fixes..."
ssh "root@$PROXMOX_HOST" "pct exec $VMID -- bash" << 'EOF'
echo "Service status:"
systemctl is-active oracle-publisher && echo "  ✓ Running" || echo "  ✗ Not running"

echo ""
echo "Recent logs:"
journalctl -u oracle-publisher -n 10 --no-pager 2>&1 | grep -E '(Price|Transaction|ERROR)' | tail -5
EOF

echo ""
log_success "========================================="
log_success "All Fixes Applied!"
log_success "========================================="
echo ""
log_info "Next steps:"
log_info "  1. Monitor logs: ssh root@$PROXMOX_HOST \"pct exec $VMID -- journalctl -u oracle-publisher -f\""
log_info "  2. Verify oracle updates: cast call 0x3304b747e565a97ec8ac220b0b6a1f6ffdb837e6 'latestRoundData()' --rpc-url https://rpc-http-pub.d-bis.org"
log_info "  3. Optional: Add CoinGecko API key for redundancy"
echo ""

