File size: 11,958 Bytes
8b7b267
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
"""
Smart Data Endpoints - NEVER Returns 404
Uses 305+ free resources with intelligent fallback
"""

import time
import logging
from typing import Optional, List
from fastapi import APIRouter, Depends, Query, HTTPException

from api.hf_auth import verify_hf_token
from utils.logger import setup_logger
import sys
sys.path.insert(0, '/workspace')
from core.smart_fallback_manager import get_fallback_manager
from workers.data_collection_agent import get_data_collection_agent

logger = setup_logger("smart_data_endpoints")

router = APIRouter(prefix="/api/smart", tags=["smart_fallback"])


@router.get("/market")
async def get_market_data_smart(
    limit: int = Query(100, ge=1, le=500, description="Number of coins"),
    auth: bool = Depends(verify_hf_token)
):
    """
    Get market data with SMART FALLBACK
    
    - Tries up to 21 different market data APIs
    - NEVER returns 404
    - Automatically switches to working source
    - Uses proxy for blocked exchanges
    - Returns data from best available source
    
    Categories tried:
    - market_data_apis (21 sources)
    - Market Data (17 sources)
    - Plus local cache
    """
    try:
        logger.info(f"πŸ” Smart Market Data Request (limit={limit})")
        
        fallback_manager = get_fallback_manager()
        
        # Try to fetch with intelligent fallback
        data = await fallback_manager.fetch_with_fallback(
            category='market_data_apis',
            endpoint_path='/coins/markets',
            params={
                'vs_currency': 'usd',
                'order': 'market_cap_desc',
                'per_page': limit,
                'page': 1
            },
            max_attempts=15  # Try up to 15 different sources
        )
        
        if not data:
            # If all fails, try alternate category
            logger.warning("⚠️ Primary category failed, trying alternate...")
            data = await fallback_manager.fetch_with_fallback(
                category='Market Data',
                endpoint_path='/v1/cryptocurrency/listings/latest',
                params={'limit': limit},
                max_attempts=10
            )
        
        if not data:
            raise HTTPException(
                status_code=503,
                detail="All data sources temporarily unavailable. Please try again in a moment."
            )
        
        # Transform data to standard format
        items = data if isinstance(data, list) else data.get('data', [])
        
        return {
            "success": True,
            "source": "smart_fallback",
            "count": len(items),
            "items": items[:limit],
            "timestamp": int(time.time() * 1000),
            "note": "Data from best available source using smart fallback"
        }
    
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"❌ Smart market data error: {e}")
        raise HTTPException(
            status_code=500,
            detail=f"Failed to fetch market data: {str(e)}"
        )


@router.get("/news")
async def get_news_smart(
    limit: int = Query(20, ge=1, le=100, description="Number of news items"),
    auth: bool = Depends(verify_hf_token)
):
    """
    Get crypto news with SMART FALLBACK
    
    - Tries 15 different news APIs
    - NEVER returns 404
    - Automatically finds working source
    """
    try:
        logger.info(f"πŸ” Smart News Request (limit={limit})")
        
        fallback_manager = get_fallback_manager()
        
        data = await fallback_manager.fetch_with_fallback(
            category='news_apis',
            endpoint_path='/news',
            params={'limit': limit},
            max_attempts=10
        )
        
        if not data:
            # Try alternate category
            data = await fallback_manager.fetch_with_fallback(
                category='News',
                endpoint_path='/v1/news',
                params={'limit': limit},
                max_attempts=5
            )
        
        if not data:
            raise HTTPException(
                status_code=503,
                detail="News sources temporarily unavailable"
            )
        
        news_items = data if isinstance(data, list) else data.get('news', [])
        
        return {
            "success": True,
            "source": "smart_fallback",
            "count": len(news_items),
            "news": news_items[:limit],
            "timestamp": int(time.time() * 1000)
        }
    
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"❌ Smart news error: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/sentiment")
async def get_sentiment_smart(
    symbol: Optional[str] = Query(None, description="Crypto symbol (e.g., BTC)"),
    auth: bool = Depends(verify_hf_token)
):
    """
    Get sentiment analysis with SMART FALLBACK
    
    - Tries 12 sentiment APIs
    - NEVER returns 404
    - Real-time sentiment from multiple sources
    """
    try:
        logger.info(f"πŸ” Smart Sentiment Request (symbol={symbol})")
        
        fallback_manager = get_fallback_manager()
        
        endpoint = f"/sentiment/{symbol}" if symbol else "/sentiment/global"
        
        data = await fallback_manager.fetch_with_fallback(
            category='sentiment_apis',
            endpoint_path=endpoint,
            max_attempts=8
        )
        
        if not data:
            data = await fallback_manager.fetch_with_fallback(
                category='Sentiment',
                endpoint_path=endpoint,
                max_attempts=5
            )
        
        if not data:
            raise HTTPException(
                status_code=503,
                detail="Sentiment sources temporarily unavailable"
            )
        
        return {
            "success": True,
            "source": "smart_fallback",
            "sentiment": data,
            "timestamp": int(time.time() * 1000)
        }
    
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"❌ Smart sentiment error: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/whale-alerts")
async def get_whale_alerts_smart(
    limit: int = Query(20, ge=1, le=100),
    auth: bool = Depends(verify_hf_token)
):
    """
    Get whale tracking alerts with SMART FALLBACK
    
    - Tries 9 whale tracking APIs
    - NEVER returns 404
    - Real-time large transactions
    """
    try:
        logger.info(f"πŸ” Smart Whale Alerts Request (limit={limit})")
        
        fallback_manager = get_fallback_manager()
        
        data = await fallback_manager.fetch_with_fallback(
            category='whale_tracking_apis',
            endpoint_path='/whales',
            params={'limit': limit},
            max_attempts=7
        )
        
        if not data:
            data = await fallback_manager.fetch_with_fallback(
                category='Whale-Tracking',
                endpoint_path='/transactions',
                params={'limit': limit},
                max_attempts=5
            )
        
        if not data:
            raise HTTPException(
                status_code=503,
                detail="Whale tracking sources temporarily unavailable"
            )
        
        alerts = data if isinstance(data, list) else data.get('transactions', [])
        
        return {
            "success": True,
            "source": "smart_fallback",
            "count": len(alerts),
            "alerts": alerts[:limit],
            "timestamp": int(time.time() * 1000)
        }
    
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"❌ Smart whale alerts error: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/blockchain/{chain}")
async def get_blockchain_data_smart(
    chain: str,
    auth: bool = Depends(verify_hf_token)
):
    """
    Get blockchain data with SMART FALLBACK
    
    - Tries 40+ block explorers
    - NEVER returns 404
    - Supports: ethereum, bsc, polygon, tron, etc.
    """
    try:
        logger.info(f"πŸ” Smart Blockchain Request (chain={chain})")
        
        fallback_manager = get_fallback_manager()
        
        data = await fallback_manager.fetch_with_fallback(
            category='block_explorers',
            endpoint_path=f'/{chain}/latest',
            max_attempts=10
        )
        
        if not data:
            data = await fallback_manager.fetch_with_fallback(
                category='Block Explorer',
                endpoint_path=f'/api?module=stats&action=ethprice',
                max_attempts=10
            )
        
        if not data:
            raise HTTPException(
                status_code=503,
                detail=f"Blockchain explorers for {chain} temporarily unavailable"
            )
        
        return {
            "success": True,
            "source": "smart_fallback",
            "chain": chain,
            "data": data,
            "timestamp": int(time.time() * 1000)
        }
    
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"❌ Smart blockchain error: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/health-report")
async def get_health_report(auth: bool = Depends(verify_hf_token)):
    """
    Get health report of all 305+ resources
    
    Shows:
    - Total resources
    - Active/degraded/failed counts
    - Top performing sources
    - Failing sources that need attention
    """
    try:
        fallback_manager = get_fallback_manager()
        agent = get_data_collection_agent()
        
        health_report = fallback_manager.get_health_report()
        agent_stats = agent.get_stats()
        
        return {
            "success": True,
            "health_report": health_report,
            "agent_stats": agent_stats,
            "timestamp": int(time.time() * 1000)
        }
    
    except Exception as e:
        logger.error(f"❌ Health report error: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/stats")
async def get_smart_stats(auth: bool = Depends(verify_hf_token)):
    """
    Get statistics about smart fallback system
    
    Shows:
    - Total resources available (305+)
    - Resources by category
    - Collection statistics
    - Performance metrics
    """
    try:
        fallback_manager = get_fallback_manager()
        agent = get_data_collection_agent()
        
        return {
            "success": True,
            "total_resources": fallback_manager._count_total_resources(),
            "resources_by_category": {
                category: len(resources)
                for category, resources in fallback_manager.resources.items()
            },
            "agent_stats": agent.get_stats(),
            "timestamp": int(time.time() * 1000)
        }
    
    except Exception as e:
        logger.error(f"❌ Stats error: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/cleanup-failed")
async def cleanup_failed_resources(
    max_age_hours: int = Query(24, description="Max age in hours"),
    auth: bool = Depends(verify_hf_token)
):
    """
    Manually trigger cleanup of failed resources
    
    Removes resources that have been failing for longer than max_age_hours
    """
    try:
        fallback_manager = get_fallback_manager()
        
        removed = fallback_manager.cleanup_failed_resources(max_age_hours=max_age_hours)
        
        return {
            "success": True,
            "removed_count": len(removed),
            "removed_resources": removed,
            "timestamp": int(time.time() * 1000)
        }
    
    except Exception as e:
        logger.error(f"❌ Cleanup error: {e}")
        raise HTTPException(status_code=500, detail=str(e))