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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
"""
News Data Collectors
Fetches cryptocurrency news from CryptoPanic and NewsAPI
"""

import asyncio
from datetime import datetime, timezone
from typing import Dict, List, Optional, Any
from utils.api_client import get_client
from utils.logger import setup_logger, log_api_request, log_error
from config import config

logger = setup_logger("news_collector")


def calculate_staleness_minutes(data_timestamp: Optional[datetime]) -> Optional[float]:
    """
    Calculate staleness in minutes from data timestamp to now

    Args:
        data_timestamp: Timestamp of the data

    Returns:
        Staleness in minutes or None if timestamp not available
    """
    if not data_timestamp:
        return None

    now = datetime.now(timezone.utc)
    if data_timestamp.tzinfo is None:
        data_timestamp = data_timestamp.replace(tzinfo=timezone.utc)

    delta = now - data_timestamp
    return delta.total_seconds() / 60.0


def parse_iso_timestamp(timestamp_str: str) -> Optional[datetime]:
    """
    Parse ISO timestamp string to datetime

    Args:
        timestamp_str: ISO format timestamp string

    Returns:
        datetime object or None if parsing fails
    """
    try:
        # Handle various ISO formats
        if timestamp_str.endswith('Z'):
            timestamp_str = timestamp_str.replace('Z', '+00:00')
        return datetime.fromisoformat(timestamp_str)
    except:
        return None


async def get_cryptopanic_posts() -> Dict[str, Any]:
    """
    Fetch latest cryptocurrency news posts from CryptoPanic

    Returns:
        Dict with provider, category, data, timestamp, staleness, success, error
    """
    provider = "CryptoPanic"
    category = "news"
    endpoint = "/posts/"

    logger.info(f"Fetching posts from {provider}")

    try:
        client = get_client()
        provider_config = config.get_provider(provider)

        if not provider_config:
            error_msg = f"Provider {provider} not configured"
            log_error(logger, provider, "config_error", error_msg, endpoint)
            return {
                "provider": provider,
                "category": category,
                "data": None,
                "timestamp": datetime.now(timezone.utc).isoformat(),
                "staleness_minutes": None,
                "success": False,
                "error": error_msg
            }

        # Build request URL
        url = f"{provider_config.endpoint_url}{endpoint}"
        params = {
            "auth_token": "free",  # CryptoPanic offers free tier
            "public": "true",
            "kind": "news",  # Get news posts
            "filter": "rising"  # Get rising news
        }

        # Make request
        response = await client.get(url, params=params, timeout=provider_config.timeout_ms // 1000)

        # Log request
        log_api_request(
            logger,
            provider,
            endpoint,
            response.get("response_time_ms", 0),
            "success" if response["success"] else "error",
            response.get("status_code")
        )

        if not response["success"]:
            error_msg = response.get("error_message", "Unknown error")
            log_error(logger, provider, response.get("error_type", "unknown"), error_msg, endpoint)
            return {
                "provider": provider,
                "category": category,
                "data": None,
                "timestamp": datetime.now(timezone.utc).isoformat(),
                "staleness_minutes": None,
                "success": False,
                "error": error_msg,
                "error_type": response.get("error_type")
            }

        # Extract data
        data = response["data"]

        # Parse timestamp from most recent post
        data_timestamp = None
        if isinstance(data, dict) and "results" in data:
            results = data["results"]
            if isinstance(results, list) and len(results) > 0:
                # Get the most recent post's timestamp
                first_post = results[0]
                if isinstance(first_post, dict) and "created_at" in first_post:
                    data_timestamp = parse_iso_timestamp(first_post["created_at"])

        staleness = calculate_staleness_minutes(data_timestamp)

        # Count posts
        post_count = 0
        if isinstance(data, dict) and "results" in data:
            post_count = len(data["results"])

        logger.info(
            f"{provider} - {endpoint} - Retrieved {post_count} posts, "
            f"staleness: {staleness:.2f}m" if staleness else "staleness: N/A"
        )

        return {
            "provider": provider,
            "category": category,
            "data": data,
            "timestamp": datetime.now(timezone.utc).isoformat(),
            "data_timestamp": data_timestamp.isoformat() if data_timestamp else None,
            "staleness_minutes": staleness,
            "success": True,
            "error": None,
            "response_time_ms": response.get("response_time_ms", 0),
            "post_count": post_count
        }

    except Exception as e:
        error_msg = f"Unexpected error: {str(e)}"
        log_error(logger, provider, "exception", error_msg, endpoint, exc_info=True)
        return {
            "provider": provider,
            "category": category,
            "data": None,
            "timestamp": datetime.now(timezone.utc).isoformat(),
            "staleness_minutes": None,
            "success": False,
            "error": error_msg,
            "error_type": "exception"
        }


async def get_newsapi_headlines() -> Dict[str, Any]:
    """
    Fetch cryptocurrency headlines from NewsAPI (newsdata.io)

    Returns:
        Dict with provider, category, data, timestamp, staleness, success, error
    """
    provider = "NewsAPI"
    category = "news"
    endpoint = "/news"

    logger.info(f"Fetching headlines from {provider}")

    try:
        client = get_client()
        provider_config = config.get_provider(provider)

        if not provider_config:
            error_msg = f"Provider {provider} not configured"
            log_error(logger, provider, "config_error", error_msg, endpoint)
            return {
                "provider": provider,
                "category": category,
                "data": None,
                "timestamp": datetime.now(timezone.utc).isoformat(),
                "staleness_minutes": None,
                "success": False,
                "error": error_msg
            }

        # Check if API key is available
        if provider_config.requires_key and not provider_config.api_key:
            error_msg = f"API key required but not configured for {provider}"
            log_error(logger, provider, "auth_error", error_msg, endpoint)
            return {
                "provider": provider,
                "category": category,
                "data": None,
                "timestamp": datetime.now(timezone.utc).isoformat(),
                "staleness_minutes": None,
                "success": False,
                "error": error_msg,
                "error_type": "missing_api_key"
            }

        # Build request URL
        url = f"{provider_config.endpoint_url}{endpoint}"
        params = {
            "apikey": provider_config.api_key,
            "q": "cryptocurrency OR bitcoin OR ethereum",
            "language": "en",
            "category": "business,technology"
        }

        # Make request
        response = await client.get(url, params=params, timeout=provider_config.timeout_ms // 1000)

        # Log request
        log_api_request(
            logger,
            provider,
            endpoint,
            response.get("response_time_ms", 0),
            "success" if response["success"] else "error",
            response.get("status_code")
        )

        if not response["success"]:
            error_msg = response.get("error_message", "Unknown error")
            log_error(logger, provider, response.get("error_type", "unknown"), error_msg, endpoint)
            return {
                "provider": provider,
                "category": category,
                "data": None,
                "timestamp": datetime.now(timezone.utc).isoformat(),
                "staleness_minutes": None,
                "success": False,
                "error": error_msg,
                "error_type": response.get("error_type")
            }

        # Extract data
        data = response["data"]

        # Parse timestamp from most recent article
        data_timestamp = None
        if isinstance(data, dict) and "results" in data:
            results = data["results"]
            if isinstance(results, list) and len(results) > 0:
                # Get the most recent article's timestamp
                first_article = results[0]
                if isinstance(first_article, dict):
                    # Try different timestamp fields
                    timestamp_field = first_article.get("pubDate") or first_article.get("publishedAt")
                    if timestamp_field:
                        data_timestamp = parse_iso_timestamp(timestamp_field)

        staleness = calculate_staleness_minutes(data_timestamp)

        # Count articles
        article_count = 0
        if isinstance(data, dict) and "results" in data:
            article_count = len(data["results"])

        logger.info(
            f"{provider} - {endpoint} - Retrieved {article_count} articles, "
            f"staleness: {staleness:.2f}m" if staleness else "staleness: N/A"
        )

        return {
            "provider": provider,
            "category": category,
            "data": data,
            "timestamp": datetime.now(timezone.utc).isoformat(),
            "data_timestamp": data_timestamp.isoformat() if data_timestamp else None,
            "staleness_minutes": staleness,
            "success": True,
            "error": None,
            "response_time_ms": response.get("response_time_ms", 0),
            "article_count": article_count
        }

    except Exception as e:
        error_msg = f"Unexpected error: {str(e)}"
        log_error(logger, provider, "exception", error_msg, endpoint, exc_info=True)
        return {
            "provider": provider,
            "category": category,
            "data": None,
            "timestamp": datetime.now(timezone.utc).isoformat(),
            "staleness_minutes": None,
            "success": False,
            "error": error_msg,
            "error_type": "exception"
        }


async def collect_news_data() -> List[Dict[str, Any]]:
    """
    Main function to collect news data from all sources

    Returns:
        List of results from all news collectors
    """
    logger.info("Starting news data collection from all sources")

    # Run all collectors concurrently
    results = await asyncio.gather(
        get_cryptopanic_posts(),
        get_newsapi_headlines(),
        return_exceptions=True
    )

    # Process results
    processed_results = []
    for result in results:
        if isinstance(result, Exception):
            logger.error(f"Collector failed with exception: {str(result)}")
            processed_results.append({
                "provider": "Unknown",
                "category": "news",
                "data": None,
                "timestamp": datetime.now(timezone.utc).isoformat(),
                "staleness_minutes": None,
                "success": False,
                "error": str(result),
                "error_type": "exception"
            })
        else:
            processed_results.append(result)

    # Log summary
    successful = sum(1 for r in processed_results if r.get("success", False))
    total_items = sum(
        r.get("post_count", 0) + r.get("article_count", 0)
        for r in processed_results if r.get("success", False)
    )

    logger.info(
        f"News data collection complete: {successful}/{len(processed_results)} successful, "
        f"{total_items} total items"
    )

    return processed_results


# Alias for backward compatibility
collect_news = collect_news_data


class NewsCollector:
    """
    News Collector class for WebSocket streaming interface
    Wraps the standalone news collection functions
    """

    def __init__(self, config: Any = None):
        """
        Initialize the news collector

        Args:
            config: Configuration object (optional, for compatibility)
        """
        self.config = config
        self.logger = logger

    async def collect(self) -> Dict[str, Any]:
        """
        Collect news data from all sources

        Returns:
            Dict with aggregated news data
        """
        results = await collect_news_data()

        # Aggregate data for WebSocket streaming
        aggregated = {
            "articles": [],
            "sources": [],
            "categories": [],
            "breaking": [],
            "timestamp": datetime.now(timezone.utc).isoformat()
        }

        for result in results:
            if result.get("success") and result.get("data"):
                provider = result.get("provider", "unknown")
                aggregated["sources"].append(provider)

                data = result["data"]

                # Parse CryptoPanic posts
                if provider == "CryptoPanic" and "results" in data:
                    for post in data["results"][:10]:  # Take top 10
                        aggregated["articles"].append({
                            "title": post.get("title"),
                            "url": post.get("url"),
                            "source": post.get("source", {}).get("title"),
                            "published_at": post.get("published_at"),
                            "kind": post.get("kind"),
                            "votes": post.get("votes", {})
                        })

                # Parse NewsAPI articles
                elif provider == "NewsAPI" and "articles" in data:
                    for article in data["articles"][:10]:  # Take top 10
                        aggregated["articles"].append({
                            "title": article.get("title"),
                            "url": article.get("url"),
                            "source": article.get("source", {}).get("name"),
                            "published_at": article.get("publishedAt"),
                            "description": article.get("description")
                        })

        return aggregated


# Example usage
if __name__ == "__main__":
    async def main():
        results = await collect_news_data()

        print("\n=== News Data Collection Results ===")
        for result in results:
            print(f"\nProvider: {result['provider']}")
            print(f"Success: {result['success']}")
            print(f"Staleness: {result.get('staleness_minutes', 'N/A')} minutes")
            if result['success']:
                print(f"Response Time: {result.get('response_time_ms', 0):.2f}ms")
                print(f"Items: {result.get('post_count', 0) + result.get('article_count', 0)}")
            else:
                print(f"Error: {result.get('error', 'Unknown')}")

    asyncio.run(main())