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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
"""

Data Access API Endpoints

Provides user-facing endpoints to access collected cryptocurrency data

"""

from datetime import datetime, timedelta
from typing import Optional, List
from fastapi import APIRouter, HTTPException, Query
from pydantic import BaseModel

from database.db_manager import db_manager
from utils.logger import setup_logger

logger = setup_logger("data_endpoints")

router = APIRouter(prefix="/api/crypto", tags=["data"])


# ============================================================================
# Pydantic Models
# ============================================================================

class PriceData(BaseModel):
    """Price data model"""
    symbol: str
    price_usd: float
    market_cap: Optional[float] = None
    volume_24h: Optional[float] = None
    price_change_24h: Optional[float] = None
    timestamp: datetime
    source: str


class NewsArticle(BaseModel):
    """News article model"""
    id: int
    title: str
    content: Optional[str] = None
    source: str
    url: Optional[str] = None
    published_at: datetime
    sentiment: Optional[str] = None
    tags: Optional[List[str]] = None


class WhaleTransaction(BaseModel):
    """Whale transaction model"""
    id: int
    blockchain: str
    transaction_hash: str
    from_address: str
    to_address: str
    amount: float
    amount_usd: float
    timestamp: datetime
    source: str


class SentimentMetric(BaseModel):
    """Sentiment metric model"""
    metric_name: str
    value: float
    classification: str
    timestamp: datetime
    source: str


# ============================================================================
# Market Data Endpoints
# ============================================================================

@router.get("/prices", response_model=List[PriceData])
async def get_all_prices(

    limit: int = Query(default=100, ge=1, le=1000, description="Number of records to return")

):
    """

    Get latest prices for all cryptocurrencies

    

    Returns the most recent price data for all tracked cryptocurrencies

    """
    try:
        prices = db_manager.get_latest_prices(limit=limit)
        
        if not prices:
            return []
        
        return [
            PriceData(
                symbol=p.symbol,
                price_usd=p.price_usd,
                market_cap=p.market_cap,
                volume_24h=p.volume_24h,
                price_change_24h=p.price_change_24h,
                timestamp=p.timestamp,
                source=p.source
            )
            for p in prices
        ]
    
    except Exception as e:
        logger.error(f"Error getting prices: {e}", exc_info=True)
        raise HTTPException(status_code=500, detail=f"Failed to get prices: {str(e)}")


@router.get("/prices/{symbol}", response_model=PriceData)
async def get_price_by_symbol(symbol: str):
    """

    Get latest price for a specific cryptocurrency

    

    Args:

        symbol: Cryptocurrency symbol (e.g., BTC, ETH, BNB)

    """
    try:
        symbol = symbol.upper()
        price = db_manager.get_latest_price_by_symbol(symbol)
        
        if not price:
            raise HTTPException(status_code=404, detail=f"Price data not found for {symbol}")
        
        return PriceData(
            symbol=price.symbol,
            price_usd=price.price_usd,
            market_cap=price.market_cap,
            volume_24h=price.volume_24h,
            price_change_24h=price.price_change_24h,
            timestamp=price.timestamp,
            source=price.source
        )
    
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Error getting price for {symbol}: {e}", exc_info=True)
        raise HTTPException(status_code=500, detail=f"Failed to get price: {str(e)}")


@router.get("/history/{symbol}")
async def get_price_history(

    symbol: str,

    hours: int = Query(default=24, ge=1, le=720, description="Number of hours of history"),

    interval: int = Query(default=60, ge=1, le=1440, description="Interval in minutes")

):
    """

    Get price history for a cryptocurrency

    

    Args:

        symbol: Cryptocurrency symbol

        hours: Number of hours of history to return

        interval: Data point interval in minutes

    """
    try:
        symbol = symbol.upper()
        history = db_manager.get_price_history(symbol, hours=hours)
        
        if not history:
            raise HTTPException(status_code=404, detail=f"No history found for {symbol}")
        
        # Sample data based on interval
        sampled = []
        last_time = None
        
        for record in history:
            if last_time is None or (record.timestamp - last_time).total_seconds() >= interval * 60:
                sampled.append({
                    "timestamp": record.timestamp.isoformat(),
                    "price_usd": record.price_usd,
                    "volume_24h": record.volume_24h,
                    "market_cap": record.market_cap
                })
                last_time = record.timestamp
        
        return {
            "symbol": symbol,
            "data_points": len(sampled),
            "interval_minutes": interval,
            "history": sampled
        }
    
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Error getting history for {symbol}: {e}", exc_info=True)
        raise HTTPException(status_code=500, detail=f"Failed to get history: {str(e)}")


@router.get("/market-overview")
async def get_market_overview():
    """

    Get market overview with top cryptocurrencies

    """
    try:
        prices = db_manager.get_latest_prices(limit=20)
        
        if not prices:
            return {
                "total_market_cap": 0,
                "total_volume_24h": 0,
                "top_gainers": [],
                "top_losers": [],
                "top_by_market_cap": []
            }
        
        # Calculate totals
        total_market_cap = sum(p.market_cap for p in prices if p.market_cap)
        total_volume_24h = sum(p.volume_24h for p in prices if p.volume_24h)
        
        # Sort by price change
        sorted_by_change = sorted(
            [p for p in prices if p.price_change_24h is not None],
            key=lambda x: x.price_change_24h,
            reverse=True
        )
        
        # Sort by market cap
        sorted_by_mcap = sorted(
            [p for p in prices if p.market_cap is not None],
            key=lambda x: x.market_cap,
            reverse=True
        )
        
        return {
            "total_market_cap": total_market_cap,
            "total_volume_24h": total_volume_24h,
            "top_gainers": [
                {
                    "symbol": p.symbol,
                    "price_usd": p.price_usd,
                    "price_change_24h": p.price_change_24h
                }
                for p in sorted_by_change[:5]
            ],
            "top_losers": [
                {
                    "symbol": p.symbol,
                    "price_usd": p.price_usd,
                    "price_change_24h": p.price_change_24h
                }
                for p in sorted_by_change[-5:]
            ],
            "top_by_market_cap": [
                {
                    "symbol": p.symbol,
                    "price_usd": p.price_usd,
                    "market_cap": p.market_cap,
                    "volume_24h": p.volume_24h
                }
                for p in sorted_by_mcap[:10]
            ],
            "timestamp": datetime.utcnow().isoformat()
        }
    
    except Exception as e:
        logger.error(f"Error getting market overview: {e}", exc_info=True)
        raise HTTPException(status_code=500, detail=f"Failed to get market overview: {str(e)}")


# ============================================================================
# News Endpoints
# ============================================================================

@router.get("/news", response_model=List[NewsArticle])
async def get_latest_news(

    limit: int = Query(default=50, ge=1, le=200, description="Number of articles"),

    source: Optional[str] = Query(default=None, description="Filter by source"),

    sentiment: Optional[str] = Query(default=None, description="Filter by sentiment")

):
    """

    Get latest cryptocurrency news

    

    Args:

        limit: Maximum number of articles to return

        source: Filter by news source

        sentiment: Filter by sentiment (positive, negative, neutral)

    """
    try:
        news = db_manager.get_latest_news(
            limit=limit,
            source=source,
            sentiment=sentiment
        )
        
        if not news:
            return []
        
        return [
            NewsArticle(
                id=article.id,
                title=article.title,
                content=article.content,
                source=article.source,
                url=article.url,
                published_at=article.published_at,
                sentiment=article.sentiment,
                tags=article.tags.split(',') if article.tags else None
            )
            for article in news
        ]
    
    except Exception as e:
        logger.error(f"Error getting news: {e}", exc_info=True)
        raise HTTPException(status_code=500, detail=f"Failed to get news: {str(e)}")


@router.get("/news/{news_id}", response_model=NewsArticle)
async def get_news_by_id(news_id: int):
    """

    Get a specific news article by ID

    """
    try:
        article = db_manager.get_news_by_id(news_id)
        
        if not article:
            raise HTTPException(status_code=404, detail=f"News article {news_id} not found")
        
        return NewsArticle(
            id=article.id,
            title=article.title,
            content=article.content,
            source=article.source,
            url=article.url,
            published_at=article.published_at,
            sentiment=article.sentiment,
            tags=article.tags.split(',') if article.tags else None
        )
    
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Error getting news {news_id}: {e}", exc_info=True)
        raise HTTPException(status_code=500, detail=f"Failed to get news: {str(e)}")


@router.get("/news/search")
async def search_news(

    q: str = Query(..., min_length=2, description="Search query"),

    limit: int = Query(default=50, ge=1, le=200)

):
    """

    Search news articles by keyword

    

    Args:

        q: Search query

        limit: Maximum number of results

    """
    try:
        results = db_manager.search_news(query=q, limit=limit)
        
        return {
            "query": q,
            "count": len(results),
            "results": [
                {
                    "id": article.id,
                    "title": article.title,
                    "source": article.source,
                    "url": article.url,
                    "published_at": article.published_at.isoformat(),
                    "sentiment": article.sentiment
                }
                for article in results
            ]
        }
    
    except Exception as e:
        logger.error(f"Error searching news: {e}", exc_info=True)
        raise HTTPException(status_code=500, detail=f"Failed to search news: {str(e)}")


# ============================================================================
# Sentiment Endpoints
# ============================================================================

@router.get("/sentiment/current")
async def get_current_sentiment():
    """

    Get current market sentiment metrics

    """
    try:
        sentiment = db_manager.get_latest_sentiment()
        
        if not sentiment:
            return {
                "fear_greed_index": None,
                "classification": "unknown",
                "timestamp": None,
                "message": "No sentiment data available"
            }
        
        return {
            "fear_greed_index": sentiment.value,
            "classification": sentiment.classification,
            "timestamp": sentiment.timestamp.isoformat(),
            "source": sentiment.source,
            "description": _get_sentiment_description(sentiment.classification)
        }
    
    except Exception as e:
        logger.error(f"Error getting sentiment: {e}", exc_info=True)
        raise HTTPException(status_code=500, detail=f"Failed to get sentiment: {str(e)}")


@router.get("/sentiment/history")
async def get_sentiment_history(

    hours: int = Query(default=168, ge=1, le=720, description="Hours of history (default: 7 days)")

):
    """

    Get sentiment history

    """
    try:
        history = db_manager.get_sentiment_history(hours=hours)
        
        return {
            "data_points": len(history),
            "history": [
                {
                    "timestamp": record.timestamp.isoformat(),
                    "value": record.value,
                    "classification": record.classification
                }
                for record in history
            ]
        }
    
    except Exception as e:
        logger.error(f"Error getting sentiment history: {e}", exc_info=True)
        raise HTTPException(status_code=500, detail=f"Failed to get sentiment history: {str(e)}")


# ============================================================================
# Whale Tracking Endpoints
# ============================================================================

@router.get("/whales/transactions", response_model=List[WhaleTransaction])
async def get_whale_transactions(

    limit: int = Query(default=50, ge=1, le=200),

    blockchain: Optional[str] = Query(default=None, description="Filter by blockchain"),

    min_amount_usd: Optional[float] = Query(default=None, ge=0, description="Minimum transaction amount in USD")

):
    """

    Get recent large cryptocurrency transactions (whale movements)

    

    Args:

        limit: Maximum number of transactions

        blockchain: Filter by blockchain (ethereum, bitcoin, etc.)

        min_amount_usd: Minimum transaction amount in USD

    """
    try:
        transactions = db_manager.get_whale_transactions(
            limit=limit,
            blockchain=blockchain,
            min_amount_usd=min_amount_usd
        )
        
        if not transactions:
            return []
        
        return [
            WhaleTransaction(
                id=tx.id,
                blockchain=tx.blockchain,
                transaction_hash=tx.transaction_hash,
                from_address=tx.from_address,
                to_address=tx.to_address,
                amount=tx.amount,
                amount_usd=tx.amount_usd,
                timestamp=tx.timestamp,
                source=tx.source
            )
            for tx in transactions
        ]
    
    except Exception as e:
        logger.error(f"Error getting whale transactions: {e}", exc_info=True)
        raise HTTPException(status_code=500, detail=f"Failed to get whale transactions: {str(e)}")


@router.get("/whales/stats")
async def get_whale_stats(

    hours: int = Query(default=24, ge=1, le=168, description="Time period in hours")

):
    """

    Get whale activity statistics

    """
    try:
        stats = db_manager.get_whale_stats(hours=hours)
        
        return {
            "period_hours": hours,
            "total_transactions": stats.get('total_transactions', 0),
            "total_volume_usd": stats.get('total_volume_usd', 0),
            "avg_transaction_usd": stats.get('avg_transaction_usd', 0),
            "largest_transaction_usd": stats.get('largest_transaction_usd', 0),
            "by_blockchain": stats.get('by_blockchain', {}),
            "timestamp": datetime.utcnow().isoformat()
        }
    
    except Exception as e:
        logger.error(f"Error getting whale stats: {e}", exc_info=True)
        raise HTTPException(status_code=500, detail=f"Failed to get whale stats: {str(e)}")


# ============================================================================
# Blockchain Data Endpoints
# ============================================================================

@router.get("/blockchain/gas")
async def get_gas_prices():
    """

    Get current gas prices for various blockchains

    """
    try:
        gas_prices = db_manager.get_latest_gas_prices()
        
        return {
            "ethereum": gas_prices.get('ethereum', {}),
            "bsc": gas_prices.get('bsc', {}),
            "polygon": gas_prices.get('polygon', {}),
            "timestamp": datetime.utcnow().isoformat()
        }
    
    except Exception as e:
        logger.error(f"Error getting gas prices: {e}", exc_info=True)
        raise HTTPException(status_code=500, detail=f"Failed to get gas prices: {str(e)}")


@router.get("/blockchain/stats")
async def get_blockchain_stats():
    """

    Get blockchain statistics

    """
    try:
        stats = db_manager.get_blockchain_stats()
        
        return {
            "ethereum": stats.get('ethereum', {}),
            "bitcoin": stats.get('bitcoin', {}),
            "bsc": stats.get('bsc', {}),
            "timestamp": datetime.utcnow().isoformat()
        }
    
    except Exception as e:
        logger.error(f"Error getting blockchain stats: {e}", exc_info=True)
        raise HTTPException(status_code=500, detail=f"Failed to get blockchain stats: {str(e)}")


# ============================================================================
# Helper Functions
# ============================================================================

def _get_sentiment_description(classification: str) -> str:
    """Get human-readable description for sentiment classification"""
    descriptions = {
        "extreme_fear": "Extreme Fear - Investors are very worried",
        "fear": "Fear - Investors are concerned",
        "neutral": "Neutral - Market is balanced",
        "greed": "Greed - Investors are getting greedy",
        "extreme_greed": "Extreme Greed - Market may be overheated"
    }
    return descriptions.get(classification, "Unknown sentiment")