name: Validate Token List

on:
  push:
    paths:
      - 'metamask/token-list.json'
      - '.github/workflows/validate-token-list.yml'
  pull_request:
    paths:
      - 'metamask/token-list.json'
      - '.github/workflows/validate-token-list.yml'

jobs:
  validate:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      
      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: '20'
      
      - name: Install dependencies
        run: |
          npm install -g ajv-cli
      
      - name: Validate JSON schema
        run: |
          ajv validate -s metamask/token-list.schema.json -d metamask/token-list.json
      
      - name: Validate token addresses
        run: |
          node -e "
          const fs = require('fs');
          const list = JSON.parse(fs.readFileSync('metamask/token-list.json', 'utf8'));
          const addressRegex = /^0x[a-fA-F0-9]{40}$/;
          list.tokens.forEach((token, i) => {
            if (!addressRegex.test(token.address)) {
              throw new Error(\`Token \${i}: Invalid address format: \${token.address}\`);
            }
            if (token.chainId !== 138) {
              throw new Error(\`Token \${i}: Invalid chainId: \${token.chainId}\`);
            }
            if (token.decimals < 0 || token.decimals > 18) {
              throw new Error(\`Token \${i}: Invalid decimals: \${token.decimals}\`);
            }
          });
          console.log('Token list validation passed');
          "
      
      - name: Check logo availability
        run: |
          node -e "
          const fs = require('fs');
          const https = require('https');
          const list = JSON.parse(fs.readFileSync('metamask/token-list.json', 'utf8'));
          const promises = [];
          if (list.logoURI) promises.push(checkUrl(list.logoURI));
          list.tokens.forEach(token => {
            if (token.logoURI) promises.push(checkUrl(token.logoURI));
          });
          Promise.all(promises).then(() => console.log('Logo URLs validated'));
          
          function checkUrl(url) {
            return new Promise((resolve, reject) => {
              https.get(url, (res) => {
                if (res.statusCode === 200) resolve();
                else reject(new Error(\`Failed to fetch \${url}: \${res.statusCode}\`));
              }).on('error', reject);
            });
          }
          " || echo "Warning: Logo URL validation failed (may be expected for local development)"

