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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
"""
Optimized CoinDesk API Client with Smart Market Discovery and Endpoint Compatibility
Enhanced version with improved error handling and market validation
"""

import argparse
import json
import os
from client import BaseClient, APIError
from typing import Union, List, Optional, Dict, Tuple
from datetime import datetime, timedelta
import time
from dataclasses import dataclass
from enum import Enum
import sys

def safe_print(*args, **kwargs):
    """Prints unicode safely even if the terminal encoding is not UTF-8."""
    text = " ".join(str(arg) for arg in args)
    try:
        sys.stdout.buffer.write((text + '\n').encode('utf-8', errors='replace'))
    except Exception:
        # Fallback to plain print if all else fails
        print(text.encode('ascii', errors='replace').decode('ascii'), **kwargs)

import config

import pathlib

def ensure_data_dir():
    """Ensure the data directory exists."""
    data_dir = pathlib.Path("dta/coindesk/indexes")
    data_dir.mkdir(parents=True, exist_ok=True)
    return data_dir

def save_json_result(filename: str, data: dict):
    """Save data as JSON to the dta/coindesk/indexes directory."""
    data_dir = ensure_data_dir()
    file_path = data_dir / filename
    with open(file_path, "w", encoding="utf-8") as f:
        json.dump(data, f, ensure_ascii=False, indent=2)

class EndpointStatus(Enum):
    SUPPORTED = "supported"
    UNSUPPORTED = "unsupported"
    UNKNOWN = "unknown"

@dataclass
class MarketInfo:
    """Market information with endpoint compatibility"""
    market_id: str
    name: str
    endpoints: Dict[str, EndpointStatus]
    instruments: List[str]
    last_checked: datetime

class IndexClient(BaseClient):
    """
    Enhanced Index & Reference Rates endpoints for CoinDesk Data API.
    Includes smart market discovery and endpoint compatibility checking.
    """
    
    def __init__(self):
        super().__init__()
        self._market_cache = {}
        self._endpoint_compatibility = {}

    def list_markets(self) -> dict:
        """List all available markets (index families)."""
        return self.get("/index/cc/v1/markets")

    def list_markets_instruments(self,
                                market: str,
                                instruments: Optional[List[str]] = None,
                                instrument_status: str = "ACTIVE"
                               ) -> dict:
        """
        List instruments for a given market. If instruments is None,
        retrieves *all* mapped instruments from the API.
        """
        params = {
            "market": market,
            "instrument_status": instrument_status
        }
        if instruments:
            params["instruments"] = ",".join(instruments)
        return self.get("/index/cc/v1/markets/instruments", params=params)

    def get_latest_tick(self, market: str, instruments: List[str], 
                       apply_mapping: bool = True) -> dict:
        """
        Latest OHLCV+ tick data.
        
        Args:
            market: Index family identifier (e.g., 'sda', 'cdifti')
            instruments: List of instrument tickers (e.g., ['XBX-USD', 'ETX-USD'])
            apply_mapping: Whether to apply instrument mapping
        """
        if not instruments:
            raise ValueError("The 'instruments' parameter is required")
        
        params = {
            'market': market,
            'instruments': ','.join(instruments),
            'apply_mapping': str(apply_mapping).lower()
        }
        
        return self.get("/index/cc/v1/latest/tick", params=params)

    def get_historical_days(self, market: str, instrument: str, limit: int = 30,
                           aggregate: int = 1, fill: bool = True, 
                           apply_mapping: bool = True, response_format: str = "JSON") -> dict:
        """
        Historical OHLCV+ by day.
        
        Args:
            market: Index family identifier (e.g., 'sda', 'cdifti')
            instrument: Single instrument ticker (e.g., 'XBX-USD')
            limit: Number of days to retrieve
            aggregate: Aggregation period
            fill: Whether to fill missing data
            apply_mapping: Whether to apply instrument mapping
            response_format: Response format
        """
        if not instrument:
            raise ValueError("The 'instrument' parameter is required")
            
        params = {
            'market': market,
            'instrument': instrument,
            'limit': limit,
            'aggregate': aggregate,
            'fill': str(fill).lower(),
            'apply_mapping': str(apply_mapping).lower(),
            'response_format': response_format
        }
        
        return self.get("/index/cc/v1/historical/days", params=params)

    def get_latest_instrument_metadata(self, market: str, instruments: List[str],
                                     apply_mapping: bool = True) -> dict:
        """
        Latest instrument metadata.
        
        Args:
            market: Index family identifier (e.g., 'sda', 'cdifti')
            instruments: List of instrument tickers (e.g., ['XBX-USD', 'ETX-USD'])
            apply_mapping: Whether to apply instrument mapping
        """
        if not instruments:
            raise ValueError("The 'instruments' parameter is required")
            
        params = {
            'market': market,
            'instruments': ','.join(instruments),
            'apply_mapping': str(apply_mapping).lower()
        }
        
        return self.get("/index/cc/v1/latest/instrument/metadata", params=params)

    def list_eod_markets_instruments(self, market: str, instruments: List[str] = None,
                                   instrument_status: str = "ACTIVE") -> dict:
        """
        List EOD (unmapped) instruments - most reliable for instrument discovery.
        
        Args:
            market: Index family identifier (e.g., 'cdifti')
            instruments: Optional list of instruments to filter
            instrument_status: Status filter (default: 'ACTIVE')
        """
        params = {
            'market': market,
            'instrument_status': instrument_status
        }
        if instruments:
            params['instruments'] = ','.join(instruments)
            
        return self.get("/index/cc/v1/markets/instruments/unmapped/eod", params=params)

    def get_historical_days_eod(self, market: str, instrument: str, limit: int = 5,
                               response_format: str = "JSON") -> dict:
        """
        EOD historical OHLCV+ by day.
        
        Args:
            market: Index family identifier (e.g., 'cdifti')
            instrument: Single instrument ticker
            limit: Number of days to retrieve
            response_format: Response format
        """
        params = {
            'market': market,
            'instrument': instrument,
            'limit': limit,
            'response_format': response_format
        }
        
        return self.get("/index/cc/v1/historical/days/eod", params=params)

    def check_endpoint_compatibility(self, market: str) -> Dict[str, EndpointStatus]:
        """
        Check which endpoints are supported for a specific market.
        
        Args:
            market: Market identifier to check
            
        Returns:
            Dictionary mapping endpoint names to their support status
        """
        if market in self._endpoint_compatibility:
            return self._endpoint_compatibility[market]
        
        endpoints = {}
        test_instruments = ["BTC-USD", "ETH-USD", "XBX-USD"]  # Common test instruments
        
        # Test EOD instruments endpoint
        try:
            self.list_eod_markets_instruments(market=market)
            endpoints["eod_instruments"] = EndpointStatus.SUPPORTED
        except APIError as e:
            endpoints["eod_instruments"] = EndpointStatus.UNSUPPORTED if e.status_code == 400 else EndpointStatus.UNKNOWN
        except Exception:
            endpoints["eod_instruments"] = EndpointStatus.UNKNOWN
        
        # Test mapped instruments endpoint (requires valid instruments)
        try:
            # First try to get some instruments
            instruments = self.discover_instruments_for_market(market, silent=True)
            if instruments:
                self.list_markets_instruments(market=market, instruments=instruments[:2])
                endpoints["mapped_instruments"] = EndpointStatus.SUPPORTED
            else:
                endpoints["mapped_instruments"] = EndpointStatus.UNKNOWN
        except APIError as e:
            endpoints["mapped_instruments"] = EndpointStatus.UNSUPPORTED if e.status_code == 400 else EndpointStatus.UNKNOWN
        except Exception:
            endpoints["mapped_instruments"] = EndpointStatus.UNKNOWN
        
        # Test tick data endpoint
        try:
            instruments = self.discover_instruments_for_market(market, silent=True)
            if instruments:
                self.get_latest_tick(market=market, instruments=instruments[:2])
                endpoints["tick_data"] = EndpointStatus.SUPPORTED
            else:
                endpoints["tick_data"] = EndpointStatus.UNKNOWN
        except APIError as e:
            endpoints["tick_data"] = EndpointStatus.UNSUPPORTED if e.status_code in [400, 404] else EndpointStatus.UNKNOWN
        except Exception:
            endpoints["tick_data"] = EndpointStatus.UNKNOWN
        
        # Test historical data endpoint
        try:
            instruments = self.discover_instruments_for_market(market, silent=True)
            if instruments:
                self.get_historical_days(market=market, instrument=instruments[0], limit=1)
                endpoints["historical_data"] = EndpointStatus.SUPPORTED
            else:
                endpoints["historical_data"] = EndpointStatus.UNKNOWN
        except APIError as e:
            endpoints["historical_data"] = EndpointStatus.UNSUPPORTED if e.status_code in [400, 404] else EndpointStatus.UNKNOWN
        except Exception:
            endpoints["historical_data"] = EndpointStatus.UNKNOWN
        
        # Test metadata endpoint
        try:
            instruments = self.discover_instruments_for_market(market, silent=True)
            if instruments:
                self.get_latest_instrument_metadata(market=market, instruments=instruments[:2])
                endpoints["metadata"] = EndpointStatus.SUPPORTED
            else:
                endpoints["metadata"] = EndpointStatus.UNKNOWN
        except APIError as e:
            endpoints["metadata"] = EndpointStatus.UNSUPPORTED if e.status_code in [400, 404] else EndpointStatus.UNKNOWN
        except Exception:
            endpoints["metadata"] = EndpointStatus.UNKNOWN
        
        self._endpoint_compatibility[market] = endpoints
        return endpoints

    def discover_markets_with_compatibility(self) -> List[MarketInfo]:
        """
        Discover all markets with their endpoint compatibility and instruments.
        
        Returns:
            List of MarketInfo objects with full compatibility information
        """
        safe_print("πŸ” Discovering markets with endpoint compatibility...")
        
        try:
            resp = self.list_markets()
            raw_markets = resp.get('Data', [])
            
            if not raw_markets:
                safe_print("❌ No markets found in API response")
                return []
                
            market_infos = []
            
            for entry in raw_markets:
                if isinstance(entry, dict):
                    market_id = entry.get('market')
                    market_name = entry.get('name')
                else:
                    market_id = entry
                    market_name = None
                
                if not market_id:
                    continue
                
                safe_print(f"\nπŸ“Š Analyzing market: {market_id} ({market_name or 'Unknown'})")
                
                # Check endpoint compatibility
                endpoints = self.check_endpoint_compatibility(market_id)
                
                # Get instruments if possible
                instruments = self.discover_instruments_for_market(market_id)
                
                # Create market info
                market_info = MarketInfo(
                    market_id=market_id,
                    name=market_name or market_id,
                    endpoints=endpoints,
                    instruments=instruments,
                    last_checked=datetime.now()
                )
                
                market_infos.append(market_info)
                
                # Print compatibility summary
                supported_count = sum(1 for status in endpoints.values() if status == EndpointStatus.SUPPORTED)
                total_count = len(endpoints)
                safe_print(f"   βœ… Supported endpoints: {supported_count}/{total_count}")
                safe_print(f"   πŸ”§ Available instruments: {len(instruments)}")
                
            return market_infos
            
        except Exception as e:
            safe_print(f"❌ Error discovering markets: {e}")
            return []

    def discover_instruments_for_market(self, market: str, silent: bool = False) -> List[str]:
        """
        Discover available instruments for a specific market using multiple approaches.
        
        Args:
            market: Market identifier (e.g., 'sda', 'cdifti')
            silent: If True, suppress output messages
        
        Returns:
            List of available instrument tickers
        """
        if not silent:
            safe_print(f"πŸ” Discovering instruments for market '{market}'...")

        # 1) EOD endpoint
        try:
            eod = self.list_eod_markets_instruments(market=market)
            data = eod.get("Data", {}).get(market, {}).get("instruments", {})
            if data:
                instruments = list(data.keys())
                if not silent:
                    safe_print(f"   βœ… {len(instruments)} via EOD")
                return instruments
        except Exception as e:
            if not silent:
                safe_print(f"   ⚠️ EOD failed: {e}")

        # 2) Metadata fallback
        common = ["BTC-USD", "ETH-USD", "XBX-USD", "ETX-USD"]
        try:
            meta = self.get_latest_instrument_metadata(market, common)
            if meta.get("Data"):
                instruments = list(meta["Data"].keys())
                if not silent:
                    safe_print(f"   βœ… {len(instruments)} via metadata")
                return instruments
        except Exception as e:
            if not silent:
                safe_print(f"   ⚠️ Metadata failed: {e}")

        # 3) General mapped instruments fallback
        try:
            mapped = self.list_markets_instruments(market=market)
            data = mapped.get("Data", {}).get(market, {})
            if data:
                instruments = list(data.keys())
                if not silent:
                    safe_print(f"   βœ… {len(instruments)} via general mapped endpoint")
                return instruments
        except Exception as e:
            if not silent:
                safe_print(f"   ⚠️ General mapped failed: {e}")

        if not silent:
            safe_print(f"   ❌ No instruments for {market}")
        return []

    def get_market_summary(self, market: str) -> Dict:
        """
        Get a comprehensive summary of a market's capabilities.
        
        Args:
            market: Market identifier
            
        Returns:
            Dictionary with market summary information
        """
        endpoints = self.check_endpoint_compatibility(market)
        instruments = self.discover_instruments_for_market(market, silent=True)
        
        supported_endpoints = [name for name, status in endpoints.items() if status == EndpointStatus.SUPPORTED]
        
        return {
            "market_id": market,
            "total_instruments": len(instruments),
            "sample_instruments": instruments[:5],
            "supported_endpoints": supported_endpoints,
            "endpoint_details": endpoints,
            "is_functional": len(supported_endpoints) > 0 and len(instruments) > 0
        }


def test_market_comprehensively(client: IndexClient, market: str):
    """
    Run comprehensive tests on a market with smart endpoint selection.
    
    Args:
        client: IndexClient instance
        market: Market identifier to test
    """
    safe_print(f"\n{'='*60}")
    safe_print(f"πŸ§ͺ COMPREHENSIVE MARKET TEST: {market}")
    safe_print(f"{'='*60}")
    
    # Get market summary
    summary = client.get_market_summary(market)
    
    safe_print(f"πŸ“Š Market Summary:")
    safe_print(f"   Market ID: {summary['market_id']}")
    safe_print(f"   Total Instruments: {summary['total_instruments']}")
    safe_print(f"   Functional: {'βœ…' if summary['is_functional'] else '❌'}")
    safe_print(f"   Supported Endpoints: {', '.join(summary['supported_endpoints'])}")
    
    if not summary['is_functional']:
        safe_print("⚠️  Market is not functional - skipping detailed tests")
        return
    
    instruments = summary['sample_instruments'][:3]  # Use first 3 for testing
    safe_print(f"πŸ”§ Testing with instruments: {instruments}")
    
    # Test each supported endpoint
    endpoint_tests = {
        "eod_instruments": lambda: client.list_eod_markets_instruments(market=market),
        "mapped_instruments": lambda: client.list_markets_instruments(market=market, instruments=instruments),
        "tick_data": lambda: client.get_latest_tick(market=market, instruments=instruments),
        "historical_data": lambda: client.get_historical_days(market=market, instrument=instruments[0], limit=3),
        "metadata": lambda: client.get_latest_instrument_metadata(market=market, instruments=instruments)
    }
    
    results = {}
    
    for endpoint_name, test_func in endpoint_tests.items():
        if endpoint_name in summary['supported_endpoints']:
            safe_print(f"\nπŸ§ͺ Testing {endpoint_name}...")
            try:
                response = test_func()
                data_count = len(response.get('Data', []))
                results[endpoint_name] = "βœ… SUCCESS"
                safe_print(f"   βœ… SUCCESS - Retrieved {data_count} data points")
                safe_print(f"   πŸ“‹ Response keys: {list(response.keys())}")
            except Exception as e:
                results[endpoint_name] = f"❌ FAILED: {str(e)[:100]}"
                safe_print(f"   ❌ FAILED: {str(e)[:100]}")
        else:
            results[endpoint_name] = "⏭️  SKIPPED (unsupported)"
            safe_print(f"\n⏭️  Skipping {endpoint_name} (unsupported)")
    
    # Print test summary
    safe_print(f"\nπŸ“‹ Test Results Summary:")
    for endpoint, result in results.items():
        safe_print(f"   {endpoint}: {result}")
    
    safe_print(f"\n{'='*60}")



def fetch_all_functional_markets():
    """
    Fetch latest tick and 30-day history for BTC-USD, SOL-USD, ETH-USD
    across all functional markets.
    Save results in dta/coindesk/indexes.
    """
    import config
    from client import APIError

    if not config.API_KEY:
        safe_print("❌ Error: COINDESK_API_KEY not set.")
        return

    client = IndexClient()
    safe_print("πŸš€ Fetching data for all functional markets and BTC/SOL/ETH...")

    markets = [
        "cadli", "ccix", "ccxrp", "ccxrpperp",
        "cd_mc", "cdi_b", "cdi_mda", "cdor", "sda"
    ]
    instruments = ["BTC-USD", "SOL-USD", "ETH-USD"]

    for m in markets:
        safe_print(f"\nπŸ“Š Market: {m}")
        market_results = {}
        for inst in instruments:
            # Latest tick
            try:
                tick = client.get_latest_tick(market=m, instruments=[inst])
                data = tick.get("Data", {}).get(inst, {})
                safe_print(f" πŸ”Έ {inst} latest price: {data.get('price', 'n/a')}")
                market_results[f"{inst}_latest_tick"] = tick
            except APIError as e:
                safe_print(f" ⚠️ {inst} tick failed (status {e.status_code})")
                market_results[f"{inst}_latest_tick"] = {"error": f"APIError {e.status_code}"}
            except Exception as e:
                safe_print(f" ⚠️ {inst} tick error: {e}")
                market_results[f"{inst}_latest_tick"] = {"error": str(e)}

            # 30-day historical
            try:
                hist = client.get_historical_days(
                    market=m,
                    instrument=inst,
                    limit=30,
                    aggregate=1,
                    fill=True
                )
                days = hist.get("Data", {}).get("values", [])
                safe_print(f"   β€’ {len(days)} days of history (first: {days[0] if days else 'n/a'})")
                market_results[f"{inst}_history"] = hist
            except APIError as e:
                safe_print(f" ⚠️ {inst} history failed (status {e.status_code})")
                market_results[f"{inst}_history"] = {"error": f"APIError {e.status_code}"}
            except Exception as e:
                safe_print(f" ⚠️ {inst} history error: {e}")
                market_results[f"{inst}_history"] = {"error": str(e)}

        # Save results for this market
        save_json_result(f"{m}.json", market_results)

if __name__ == "__main__":
    # main()
    # To run the fetch-all-markets script, uncomment below:
    fetch_all_functional_markets()