#!/usr/bin/env python3
# ROT A1: DefiLlama chain series -> /opt/rot/analyst/raw/llama/*.json
import json, os, time, urllib.request
OUT='/opt/rot/analyst/raw/llama'; os.makedirs(OUT, exist_ok=True)
UA='Mozilla/5.0 (Macintosh) Chrome/127'
CH=['Ethereum','Solana','BSC','Base','Arbitrum','Tron','Avalanche','Polygon','Sui','Hyperliquid L1','TON','Optimism','Bitcoin','Aptos','Near','Fantom','Sonic','Berachain','Blast','zkSync Era','Linea','Mantle','Cronos','Injective','Osmosis','Cardano','Terra']
def get(u):
    req=urllib.request.Request(u,headers={'User-Agent':UA})
    with urllib.request.urlopen(req,timeout=90) as r: return json.load(r)
def save(name,u):
    p=f'{OUT}/{name}.json'
    try:
        j=get(u); json.dump(j,open(p,'w')); print('ok',name,flush=True)
    except Exception as e: print('FAIL',name,str(e)[:80],flush=True)
    time.sleep(0.5)
save('stables_all','https://stablecoins.llama.fi/stablecoincharts/all')
save('stables_chains','https://stablecoins.llama.fi/stablecoinchains')
save('dex_all','https://api.llama.fi/overview/dexs?excludeTotalDataChartBreakdown=false&excludeTotalDataChart=false&dataType=dailyVolume')
save('fees_all','https://api.llama.fi/overview/fees?excludeTotalDataChartBreakdown=false&excludeTotalDataChart=false&dataType=dailyFees')
for c in CH:
    q=urllib.parse.quote(c) if False else c.replace(' ','%20')
    save(f'tvl_{c}',f'https://api.llama.fi/v2/historicalChainTvl/{q}')
    save(f'stables_{c}',f'https://stablecoins.llama.fi/stablecoincharts/{q}')
    save(f'dex_{c}',f'https://api.llama.fi/overview/dexs/{q}?excludeTotalDataChartBreakdown=true&excludeTotalDataChart=false&dataType=dailyVolume')
    save(f'fees_{c}',f'https://api.llama.fi/overview/fees/{q}?excludeTotalDataChartBreakdown=true&excludeTotalDataChart=false&dataType=dailyFees')
