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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
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
# πŸ” Complete Diagnostic & Fix Guide
## HuggingFace Space Integration Troubleshooting

**Version:** 2.0
**Last Updated:** 2025-11-15
**Target:** Node.js/React ↔ HuggingFace Space Integration
**Space URL:** https://really-amin-datasourceforcryptocurrency.hf.space

---

## πŸ“‹ Table of Contents

1. [Quick Start Diagnostic](#quick-start-diagnostic)
2. [Pre-Flight Checks](#pre-flight-checks)
3. [Automated Diagnostic Script](#automated-diagnostic-script)
4. [Common Issues & Fixes](#common-issues--fixes)
5. [Testing Protocol](#testing-protocol)
6. [Debugging Commands](#debugging-commands)
7. [Configuration Guide](#configuration-guide)
8. [Troubleshooting Decision Tree](#troubleshooting-decision-tree)
9. [FAQ](#faq)

---

## πŸš€ Quick Start Diagnostic

### Step 1: Check HuggingFace Space Status

```bash
# Test if Space is alive
curl -v https://really-amin-datasourceforcryptocurrency.hf.space/api/health

# Expected Output:
# HTTP/2 200
# {"status": "healthy"}

# If you get:
# - Connection timeout β†’ Space is sleeping or down
# - 404 Not Found β†’ Endpoint doesn't exist
# - 503 Service Unavailable β†’ Space is building
```

### Step 2: Discover Available Endpoints

```bash
# Try common endpoints
echo "Testing /api/health..."
curl -s https://really-amin-datasourceforcryptocurrency.hf.space/api/health | jq

echo "Testing /api/prices..."
curl -s "https://really-amin-datasourceforcryptocurrency.hf.space/api/prices?symbols=BTC,ETH" | jq

echo "Testing /api/ohlcv..."
curl -s "https://really-amin-datasourceforcryptocurrency.hf.space/api/ohlcv?symbol=BTCUSDT&interval=1h&limit=10" | jq

echo "Testing /api/market/overview..."
curl -s https://really-amin-datasourceforcryptocurrency.hf.space/api/market/overview | jq

echo "Testing /api/sentiment..."
curl -s https://really-amin-datasourceforcryptocurrency.hf.space/api/sentiment | jq

echo "Testing /docs (API documentation)..."
curl -s https://really-amin-datasourceforcryptocurrency.hf.space/docs | head -n 50
```

### Step 3: Quick Application Test

```bash
# Setup environment
cp .env.example .env

# Edit .env file - set:
# PRIMARY_DATA_SOURCE=huggingface
# HF_SPACE_BASE_URL=https://really-amin-datasourceforcryptocurrency.hf.space

# Install dependencies
npm install

# Start development server
npm run dev

# Open browser and check:
# 1. http://localhost:5173
# 2. Open DevTools (F12)
# 3. Go to Network tab
# 4. Check for any red requests
# 5. Go to Console tab
# 6. Look for error messages
```

---

## βœ… Pre-Flight Checks

Before troubleshooting, verify these requirements:

### System Requirements

```bash
# Check Node.js version (should be 18+)
node --version
# Expected: v18.0.0 or higher

# Check npm version
npm --version
# Expected: 9.0.0 or higher

# Check if git is installed
git --version

# Check if curl is available
curl --version

# Check if jq is installed (optional but helpful)
jq --version
# If not installed: sudo apt-get install jq (Ubuntu) or brew install jq (Mac)
```

### Project Structure Verification

```bash
# Verify critical files exist
ls -la hf-data-engine/main.py
ls -la hf-data-engine/requirements.txt
ls -la .env.example
ls -la package.json

# If any file is missing, run:
git status
git pull origin main
```

### Dependencies Installation

```bash
# Clean install
rm -rf node_modules package-lock.json
npm install

# Install backend dependencies (FastAPI server used on HuggingFace)
pip install -r requirements.txt

# Verify critical backend packages
pip show fastapi uvicorn slowapi sqlalchemy PyJWT || true

# Verify critical packages
npm list typescript
npm list vite
npm list react

# For Python dependencies (if working with backend)
cd hf-data-engine
pip install -r requirements.txt
cd ..
```

### Environment Configuration

```bash
# Check if .env exists
if [ ! -f .env ]; then
    echo "⚠️  .env file not found!"
    echo "Creating from .env.example..."
    cp .env.example .env
else
    echo "βœ… .env file exists"
fi

# Verify required variables
grep -q "PRIMARY_DATA_SOURCE" .env && echo "βœ… PRIMARY_DATA_SOURCE configured" || echo "❌ PRIMARY_DATA_SOURCE missing"
grep -q "HF_SPACE_BASE_URL" .env && echo "βœ… HF_SPACE_BASE_URL configured" || echo "❌ HF_SPACE_BASE_URL missing"

# View current configuration (non-sensitive parts)
echo ""
echo "Current configuration:"
grep "PRIMARY_DATA_SOURCE\|HF_SPACE" .env | sed 's/=.*/=***/'
```

---

## πŸ€– Automated Diagnostic Script

Save this as `diagnostic.sh` in your project root and run with `bash diagnostic.sh`:

```bash
#!/bin/bash

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

echo "╔════════════════════════════════════════════════════════╗"
echo "β•‘   HuggingFace Space Integration Diagnostic Tool       β•‘"
echo "β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•"
echo ""

# Configuration
HF_SPACE_URL="https://really-amin-datasourceforcryptocurrency.hf.space"
RESULTS_FILE="diagnostic_results_$(date +%Y%m%d_%H%M%S).log"

# Function to print status
print_status() {
    if [ $1 -eq 0 ]; then
        echo -e "${GREEN}βœ… PASS${NC}: $2"
    else
        echo -e "${RED}❌ FAIL${NC}: $2"
    fi
}

# Function to test endpoint
test_endpoint() {
    local endpoint=$1
    local description=$2

    echo -e "\n${BLUE}Testing:${NC} $description"
    echo "Endpoint: $endpoint"

    response=$(curl -s -w "\n%{http_code}" --connect-timeout 10 "$endpoint" 2>&1)
    http_code=$(echo "$response" | tail -n1)
    body=$(echo "$response" | sed '$d')

    echo "HTTP Status: $http_code"

    if [ "$http_code" = "200" ]; then
        print_status 0 "$description"
        echo "Response preview:"
        echo "$body" | head -n 5
        return 0
    else
        print_status 1 "$description (HTTP $http_code)"
        echo "Error details:"
        echo "$body" | head -n 3
        return 1
    fi
}

# Start logging
exec > >(tee -a "$RESULTS_FILE")
exec 2>&1

echo "Starting diagnostic at $(date)"
echo "Results will be saved to: $RESULTS_FILE"
echo ""

# Test 1: System Requirements
echo "════════════════════════════════════════════════════════"
echo "TEST 1: System Requirements"
echo "════════════════════════════════════════════════════════"

node --version > /dev/null 2>&1
print_status $? "Node.js installed"

npm --version > /dev/null 2>&1
print_status $? "npm installed"

curl --version > /dev/null 2>&1
print_status $? "curl installed"

# Test 2: Project Structure
echo ""
echo "════════════════════════════════════════════════════════"
echo "TEST 2: Project Structure"
echo "════════════════════════════════════════════════════════"

[ -f "package.json" ]
print_status $? "package.json exists"

[ -f ".env.example" ]
print_status $? ".env.example exists"

[ -d "hf-data-engine" ]
print_status $? "hf-data-engine directory exists"

[ -f "hf-data-engine/main.py" ]
print_status $? "HuggingFace engine implementation exists"

# Test 3: Environment Configuration
echo ""
echo "════════════════════════════════════════════════════════"
echo "TEST 3: Environment Configuration"
echo "════════════════════════════════════════════════════════"

if [ -f ".env" ]; then
    print_status 0 ".env file exists"

    grep -q "PRIMARY_DATA_SOURCE" .env
    print_status $? "PRIMARY_DATA_SOURCE configured"

    grep -q "HF_SPACE_BASE_URL" .env
    print_status $? "HF_SPACE_BASE_URL configured"

    echo ""
    echo "Current configuration:"
    grep "PRIMARY_DATA_SOURCE\|HF_SPACE" .env | sed 's/=.*/=***/' || true
else
    print_status 1 ".env file exists"
    echo "⚠️  Run: cp .env.example .env"
fi

# Test 4: HuggingFace Space Connectivity
echo ""
echo "════════════════════════════════════════════════════════"
echo "TEST 4: HuggingFace Space Connectivity"
echo "════════════════════════════════════════════════════════"

# Test DNS resolution
echo "Resolving DNS..."
host really-amin-datasourceforcryptocurrency.hf.space > /dev/null 2>&1
print_status $? "DNS resolution for HF Space"

# Test basic connectivity
echo ""
echo "Testing basic connectivity..."
ping -c 1 -W 5 hf.space > /dev/null 2>&1
print_status $? "Network connectivity to hf.space"

# Test 5: HuggingFace Space Endpoints
echo ""
echo "════════════════════════════════════════════════════════"
echo "TEST 5: HuggingFace Space Endpoints"
echo "════════════════════════════════════════════════════════"

test_endpoint "$HF_SPACE_URL/api/health" "Health check endpoint"
test_endpoint "$HF_SPACE_URL/api/prices?symbols=BTC,ETH" "Prices endpoint"
test_endpoint "$HF_SPACE_URL/api/ohlcv?symbol=BTCUSDT&interval=1h&limit=10" "OHLCV endpoint"
test_endpoint "$HF_SPACE_URL/api/market/overview" "Market overview endpoint"
test_endpoint "$HF_SPACE_URL/api/sentiment" "Sentiment endpoint"

# Test 6: CORS Headers
echo ""
echo "════════════════════════════════════════════════════════"
echo "TEST 6: CORS Configuration"
echo "════════════════════════════════════════════════════════"

cors_headers=$(curl -s -I -H "Origin: http://localhost:5173" "$HF_SPACE_URL/api/prices" 2>&1 | grep -i "access-control")

if [ -z "$cors_headers" ]; then
    print_status 1 "CORS headers present"
    echo "⚠️  No CORS headers found. This may cause browser errors."
    echo "    Consider using Vite proxy (see Configuration Guide)."
else
    print_status 0 "CORS headers present"
    echo "CORS headers:"
    echo "$cors_headers"
fi

# Test 7: Response Format Validation
echo ""
echo "════════════════════════════════════════════════════════"
echo "TEST 7: Response Format Validation"
echo "════════════════════════════════════════════════════════"

echo "Fetching sample data..."
sample_response=$(curl -s "$HF_SPACE_URL/api/prices?symbols=BTC" 2>&1)

if command -v jq > /dev/null 2>&1; then
    echo "$sample_response" | jq . > /dev/null 2>&1
    if [ $? -eq 0 ]; then
        print_status 0 "Valid JSON response"
        echo ""
        echo "Response structure:"
        echo "$sample_response" | jq 'keys' 2>/dev/null || echo "Unable to parse keys"
    else
        print_status 1 "Valid JSON response"
        echo "Response is not valid JSON:"
        echo "$sample_response" | head -n 3
    fi
else
    echo "⚠️  jq not installed, skipping JSON validation"
    echo "Install with: sudo apt-get install jq (Ubuntu) or brew install jq (Mac)"
fi

# Test 8: Dependencies
echo ""
echo "════════════════════════════════════════════════════════"
echo "TEST 8: Node Dependencies"
echo "════════════════════════════════════════════════════════"

if [ -d "node_modules" ]; then
    print_status 0 "node_modules exists"

    [ -d "node_modules/typescript" ]
    print_status $? "TypeScript installed"

    [ -d "node_modules/vite" ]
    print_status $? "Vite installed"

    [ -d "node_modules/react" ]
    print_status $? "React installed"
else
    print_status 1 "node_modules exists"
    echo "⚠️  Run: npm install"
fi

# Test 9: Python Dependencies (if backend is present)
echo ""
echo "════════════════════════════════════════════════════════"
echo "TEST 9: Python Dependencies"
echo "════════════════════════════════════════════════════════"

if [ -f "hf-data-engine/requirements.txt" ]; then
    print_status 0 "requirements.txt exists"

    python3 -c "import fastapi" 2>/dev/null
    print_status $? "FastAPI installed"

    python3 -c "import aiohttp" 2>/dev/null
    print_status $? "aiohttp installed"
else
    print_status 1 "requirements.txt exists"
fi

# Summary
echo ""
echo "════════════════════════════════════════════════════════"
echo "DIAGNOSTIC SUMMARY"
echo "════════════════════════════════════════════════════════"

echo ""
echo "Results saved to: $RESULTS_FILE"
echo ""
echo "Next steps:"
echo "1. Review any failed tests above"
echo "2. Check the 'Common Issues & Fixes' section in HUGGINGFACE_DIAGNOSTIC_GUIDE.md"
echo "3. Run 'npm run dev' and test in browser"
echo ""
echo "Diagnostic completed at $(date)"
```

Make it executable and run:

```bash
chmod +x diagnostic.sh
./diagnostic.sh
```

---

## πŸ”§ Common Issues & Fixes

### Issue 1: HuggingFace Space is Sleeping/Down

**Symptoms:**
- `curl: (28) Connection timed out`
- `503 Service Unavailable`
- `Connection refused`
- Space shows "Building" or "Sleeping" on HuggingFace.co

**Root Cause:**
HuggingFace Spaces with free resources go to sleep after 48 hours of inactivity. They need to be "woken up" with a request.

**Diagnosis:**

```bash
# Check Space status via HuggingFace website
# Visit: https://huggingface.co/spaces/Really-amin/Datasourceforcryptocurrency

# Or test via API
curl -v https://really-amin-datasourceforcryptocurrency.hf.space/api/health

# Expected responses:
# 200 = Space is awake βœ…
# 503 = Space is starting (wait 60 seconds)
# Timeout = Space is sleeping
```

**Fix Option 1: Wake Up the Space**

```bash
# Send a request to wake it up
curl https://really-amin-datasourceforcryptocurrency.hf.space/api/health

# Wait 30-60 seconds for Space to start
echo "Waiting for Space to start..."
sleep 60

# Try again
curl -s https://really-amin-datasourceforcryptocurrency.hf.space/api/health | jq

# You should see: {"status": "healthy"}
```

**Fix Option 2: Use Fallback Source**

```bash
# Edit .env
nano .env

# Add these settings:
PRIMARY_DATA_SOURCE=coingecko
FALLBACK_ENABLED=true
FALLBACK_SOURCES=coincap,binance

# Restart application
npm run dev
```

**Fix Option 3: Keep Space Awake (Linux/Mac)**

Create a persistent ping job:

```bash
# Edit crontab
crontab -e

# Add this line (runs every 10 minutes):
*/10 * * * * curl -s https://really-amin-datasourceforcryptocurrency.hf.space/api/health > /dev/null

# Verify cron was added
crontab -l
```

**Fix Option 4: Upgrade HuggingFace Space (Recommended)**

```
Contact HuggingFace to upgrade to paid resources for 24/7 uptime.
Visit: https://huggingface.co/spaces/Really-amin/Datasourceforcryptocurrency/settings
```

---

### Issue 2: Wrong API Endpoints (404 Errors)

**Symptoms:**
- `404 Not Found`
- `Cannot GET /api/crypto/prices/top`
- Empty response or HTML error page
- Console shows: `404: Not Found`

**Root Cause:**
The actual API endpoints don't match what's configured in your application.

**Diagnosis:**

```bash
# Discover actual endpoints by checking API docs
curl -s https://really-amin-datasourceforcryptocurrency.hf.space/docs | grep -oP 'href="[^"]*"' | head -20

# Or try different endpoint patterns manually
echo "Pattern 1: /api/prices"
curl -s https://really-amin-datasourceforcryptocurrency.hf.space/api/prices?symbols=BTC

echo ""
echo "Pattern 2: /prices"
curl -s https://really-amin-datasourceforcryptocurrency.hf.space/prices?symbols=BTC

echo ""
echo "Pattern 3: /v1/prices"
curl -s https://really-amin-datasourceforcryptocurrency.hf.space/v1/prices?symbols=BTC

echo ""
echo "Pattern 4: Root endpoint"
curl -s https://really-amin-datasourceforcryptocurrency.hf.space/ | head -n 20

# Check actual response format
curl -s https://really-amin-datasourceforcryptocurrency.hf.space/api/health | jq
```

**Fix: Update Adapter Configuration**

First, locate your adapter file:

```bash
find . -name "*huggingface*adapter*" -o -name "*hf*adapter*"
```

Then update the endpoint configuration:

**Option A: If using configuration object**

```typescript
// src/config/huggingface.ts or similar
export const huggingfaceConfig = {
  baseUrl: 'https://really-amin-datasourceforcryptocurrency.hf.space',
  endpoints: {
    prices: '/api/prices',           // Verify this path exists
    ohlcv: '/api/ohlcv',
    sentiment: '/api/sentiment',
    market: '/api/market/overview',
    health: '/api/health'
  },
  timeout: 30000,
};
```

**Option B: If endpoints need transformation**

```typescript
// src/services/adapters/huggingface.adapter.ts

private getEndpointPath(endpoint: string): string {
  // Map application endpoints to actual Space endpoints
  const endpointMap: Record<string, string> = {
    '/prices': '/api/prices',
    '/ohlcv': '/api/ohlcv',
    '/sentiment': '/api/sentiment',
    '/market-overview': '/api/market/overview',
  };

  return endpointMap[endpoint] || endpoint;
}

async fetchData(endpoint: string): Promise<any> {
  const actualEndpoint = this.getEndpointPath(endpoint);
  const url = `${this.baseUrl}${actualEndpoint}`;

  console.log(`Fetching from: ${url}`);

  const response = await fetch(url, {
    method: 'GET',
    headers: this.getHeaders(),
  });

  if (!response.ok) {
    throw new Error(`HTTP ${response.status}: ${response.statusText}`);
  }

  return response.json();
}
```

**Option C: Add debugging**

```typescript
// Temporary debugging to find correct endpoints
async discoverEndpoints(): Promise<void> {
  const patterns = [
    '/api/prices',
    '/api/price',
    '/prices',
    '/v1/prices',
    '/price',
  ];

  for (const pattern of patterns) {
    try {
      const response = await fetch(`${this.baseUrl}${pattern}?symbols=BTC`, {
        timeout: 5000
      });
      console.log(`${pattern}: HTTP ${response.status}`);
    } catch (error) {
      console.log(`${pattern}: Error -`, error);
    }
  }
}

// Call this during development
// await adapter.discoverEndpoints();
```

---

### Issue 3: Response Format Mismatch

**Symptoms:**
- Data shows as `undefined` in UI
- Console errors: `Cannot read property 'symbol' of undefined`
- TypeScript type errors
- Numbers showing as strings

**Root Cause:**
The Space returns data in a different format than expected.

**Diagnosis:**

```bash
# Get actual response and examine structure
curl -s "https://really-amin-datasourceforcryptocurrency.hf.space/api/prices?symbols=BTC,ETH" | jq '.' -C

# Note the field names, types, and structure

# Compare with expected format
# Expected example:
# [
#   {
#     "symbol": "BTC",
#     "price": 50000,
#     "change24h": 2.5
#   }
# ]

# Actual format (if different):
# {
#   "data": [
#     {
#       "coin": "bitcoin",
#       "current_price": "50000.00",
#       "percent_change": "2.5"
#     }
#   ]
# }
```

**Fix: Update Data Mapping**

```typescript
// src/services/adapters/huggingface.adapter.ts

interface HFPriceResponse {
  // Define actual Space response structure
  data?: Array<{
    coin?: string;
    symbol?: string;
    current_price?: number | string;
    price?: number | string;
    percent_change?: number | string;
    change_24h?: number | string;
  }>;
  prices?: any[];
}

async getPrices(symbols: string[]): Promise<CryptoPrice[]> {
  const data = await this.fetchData<HFPriceResponse>('/api/prices?symbols=' + symbols.join(','));

  // Handle different response structures
  const prices = data.data || data.prices || [];

  return prices.map(item => {
    // Safely extract values with fallbacks
    const symbol = item.symbol || item.coin?.toUpperCase() || 'UNKNOWN';
    const price = Number(item.current_price || item.price || 0);
    const change24h = Number(item.percent_change || item.change_24h || 0);

    // Validate required fields
    if (isNaN(price)) {
      console.warn(`Invalid price for ${symbol}:`, item);
      return null;
    }

    return {
      symbol,
      price,
      change24h,
      timestamp: Date.now(),
    };
  }).filter(Boolean) as CryptoPrice[];
}
```

**Add Comprehensive Validation:**

```typescript
// src/services/validators/huggingface.validator.ts

export function validatePriceResponse(data: any): boolean {
  if (!Array.isArray(data) && !data?.data && !data?.prices) {
    console.error('Invalid response structure:', typeof data);
    return false;
  }

  const items = Array.isArray(data) ? data : (data.data || data.prices || []);

  if (items.length === 0) {
    console.warn('Response contains no items');
    return false;
  }

  // Validate first item has required fields
  const firstItem = items[0];
  if (!firstItem.symbol && !firstItem.coin) {
    console.error('Missing symbol/coin field:', firstItem);
    return false;
  }

  if (!firstItem.price && !firstItem.current_price) {
    console.error('Missing price field:', firstItem);
    return false;
  }

  return true;
}

export function normalizePriceData(data: any): CryptoPrice[] {
  if (!validatePriceResponse(data)) {
    throw new Error('Invalid price response format');
  }

  const items = Array.isArray(data) ? data : (data.data || data.prices);

  return items.map((item: any) => ({
    symbol: (item.symbol || item.coin || 'UNKNOWN').toUpperCase(),
    price: Number(item.current_price || item.price || 0),
    change24h: Number(item.percent_change || item.change_24h || 0),
    timestamp: Date.now(),
  }));
}
```

---

### Issue 4: CORS Errors in Browser

**Symptoms:**
- Browser console error: `Access to fetch at '...' from origin 'http://localhost:5173' has been blocked by CORS policy`
- Network tab shows request with red X
- `No 'Access-Control-Allow-Origin' header is present`

**Root Cause:**
Browser blocks cross-origin requests unless the server includes proper CORS headers.

**Diagnosis:**

```bash
# Check if Space returns CORS headers
curl -I -H "Origin: http://localhost:5173" \
  https://really-amin-datasourceforcryptocurrency.hf.space/api/prices

# Look for these headers in the response:
# Access-Control-Allow-Origin: *
# Access-Control-Allow-Methods: GET, POST, OPTIONS
# Access-Control-Allow-Headers: Content-Type

# If headers are missing, you'll see CORS errors in browser

# Test with preflight OPTIONS request
curl -X OPTIONS -I \
  -H "Origin: http://localhost:5173" \
  -H "Access-Control-Request-Method: GET" \
  https://really-amin-datasourceforcryptocurrency.hf.space/api/prices
```

**Fix Option 1: Add Vite Proxy (Recommended for Development)**

```typescript
// vite.config.ts

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'

export default defineConfig({
  plugins: [react()],
  server: {
    proxy: {
      '/api/hf': {
        target: 'https://really-amin-datasourceforcryptocurrency.hf.space',
        changeOrigin: true,
        rewrite: (path) => {
          // Remove /api/hf prefix and keep the rest
          return path.replace(/^\/api\/hf/, '');
        },
        configure: (proxy, options) => {
          proxy.on('error', (err, req, res) => {
            console.error('Proxy error:', err);
          });
          proxy.on('proxyReq', (proxyReq, req, res) => {
            console.log('Proxying:', req.method, req.url);
          });
          proxy.on('proxyRes', (proxyRes, req, res) => {
            console.log('Proxy response:', proxyRes.statusCode);
          });
        }
      }
    }
  }
})
```

Then update your adapter:

```typescript
// src/services/adapters/huggingface.adapter.ts

async fetchData<T>(endpoint: string): Promise<T> {
  // In development, use Vite proxy
  // In production, use direct URL (if CORS enabled on Space)

  const baseUrl = import.meta.env.DEV
    ? '/api/hf'  // Proxied through Vite
    : this.config.baseUrl;  // Direct to Space

  const url = `${baseUrl}${endpoint}`;

  console.log(`[${import.meta.env.DEV ? 'DEV' : 'PROD'}] Fetching: ${url}`);

  const response = await fetch(url, {
    method: 'GET',
    headers: this.getHeaders(),
    signal: AbortSignal.timeout(this.config.timeout),
  });

  if (!response.ok) {
    const errorText = await response.text();
    throw new Error(`HTTP ${response.status}: ${errorText}`);
  }

  return response.json();
}
```

**Fix Option 2: Update Space with CORS Headers (If you control the Space)**

If you control the HuggingFace Space, add CORS support:

**For FastAPI-based Space:**

```python
# hf-data-engine/main.py

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

app = FastAPI(title="Crypto Data Engine")

# Add CORS middleware
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # Or specify: ["http://localhost:5173", "https://yourdomain.com"]
    allow_credentials=True,
    allow_methods=["GET", "POST", "OPTIONS"],
    allow_headers=["*", "Content-Type", "Authorization"],
    max_age=3600,  # Cache preflight for 1 hour
)

@app.get("/api/health")
async def health():
    return {"status": "healthy"}

# ... rest of API endpoints
```

**For Gradio-based Space:**

```python
# app.py

import gradio as gr

# Create your interface
demo = gr.Blocks()

with demo:
    # Your components here
    pass

if __name__ == "__main__":
    demo.launch(
        share=True,
        server_name="0.0.0.0",
        server_port=7860,
        # Note: Gradio automatically handles CORS for public access
    )
```

**Fix Option 3: Use CORS Proxy Service (Development Only)**

⚠️ **Not recommended for production**

```typescript
// src/services/adapters/huggingface.adapter.ts

async fetchData<T>(endpoint: string): Promise<T> {
  let url = `${this.config.baseUrl}${endpoint}`;

  // Only use CORS proxy as last resort for testing
  if (import.meta.env.DEV && !import.meta.env.VITE_USE_PROXY) {
    const corsProxy = 'https://corsproxy.io/?';
    url = corsProxy + encodeURIComponent(url);
  }

  const response = await fetch(url);
  return response.json();
}
```

Available CORS proxy services (for testing only):
- https://corsproxy.io/
- https://cors-anywhere.herokuapp.com/
- https://api.allorigins.win/

---

### Issue 5: Timeout Errors

**Symptoms:**
- `AbortError: The operation was aborted due to timeout`
- Requests take > 30 seconds
- UI shows loading spinner that never completes
- Network tab shows request taking a long time

**Root Cause:**
Space is slow to respond or having performance issues, or timeout is too short.

**Diagnosis:**

```bash
# Measure actual response time
time curl -s https://really-amin-datasourceforcryptocurrency.hf.space/api/prices?symbols=BTC | jq > /dev/null

# Expected: < 5 seconds
# 5-15 seconds: Space is cold (starting up)
# > 30 seconds: Space might be sleeping or overloaded

# Check Space status
curl -I https://really-amin-datasourceforcryptocurrency.hf.space/api/health

# Test endpoint directly multiple times
for i in {1..3}; do
  echo "Request $i:"
  time curl -s https://really-amin-datasourceforcryptocurrency.hf.space/api/prices?symbols=BTC > /dev/null
  echo ""
done
```

**Fix Option 1: Increase Timeout**

```typescript
// .env
HF_REQUEST_TIMEOUT=60000  # 60 seconds

// src/config/huggingface.ts
export const huggingfaceConfig = {
  baseUrl: 'https://really-amin-datasourceforcryptocurrency.hf.space',
  timeout: parseInt(import.meta.env.VITE_HF_REQUEST_TIMEOUT || '60000'),
};

// src/services/adapters/huggingface.adapter.ts
async fetchData<T>(endpoint: string): Promise<T> {
  const url = `${this.config.baseUrl}${endpoint}`;

  console.log(`[HF] Requesting ${endpoint} (timeout: ${this.config.timeout}ms)`);

  const startTime = Date.now();

  try {
    const response = await fetch(url, {
      signal: AbortSignal.timeout(this.config.timeout),
    });

    const duration = Date.now() - startTime;
    console.log(`[HF] Completed in ${duration}ms`);

    return response.json();
  } catch (error) {
    const duration = Date.now() - startTime;
    console.error(`[HF] Failed after ${duration}ms:`, error);
    throw error;
  }
}
```

**Fix Option 2: Implement Proper Loading States**

```typescript
// src/hooks/useHuggingFaceData.ts

import { useState, useEffect } from 'react';

export function useHuggingFaceData<T>(
  fetchFn: () => Promise<T>,
  options?: { timeout?: number; retries?: number }
) {
  const [data, setData] = useState<T | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<Error | null>(null);

  useEffect(() => {
    let mounted = true;
    let retryCount = 0;
    const maxRetries = options?.retries ?? 1;

    async function fetchData() {
      try {
        setLoading(true);
        setError(null);

        const result = await fetchFn();

        if (mounted) {
          setData(result);
        }
      } catch (err) {
        if (mounted) {
          if (retryCount < maxRetries) {
            retryCount++;
            console.log(`Retrying... (${retryCount}/${maxRetries})`);
            setTimeout(fetchData, 2000 * retryCount); // Exponential backoff
          } else {
            setError(err instanceof Error ? err : new Error('Unknown error'));
          }
        }
      } finally {
        if (mounted) {
          setLoading(retryCount === 0 || retryCount === maxRetries);
        }
      }
    }

    fetchData();

    return () => { mounted = false; };
  }, [fetchFn, options?.retries]);

  return { data, loading, error };
}
```

**Fix Option 3: Implement Caching**

```typescript
// src/services/cache/huggingface.cache.ts

interface CacheEntry<T> {
  data: T;
  timestamp: number;
  ttl: number;
}

export class HuggingFaceCache {
  private cache = new Map<string, CacheEntry<any>>();
  private defaultTTL = 5 * 60 * 1000; // 5 minutes

  set<T>(key: string, data: T, ttl?: number): void {
    this.cache.set(key, {
      data,
      timestamp: Date.now(),
      ttl: ttl || this.defaultTTL,
    });
  }

  get<T>(key: string): T | null {
    const entry = this.cache.get(key) as CacheEntry<T> | undefined;

    if (!entry) return null;

    const age = Date.now() - entry.timestamp;
    if (age > entry.ttl) {
      this.cache.delete(key);
      return null;
    }

    return entry.data;
  }

  isStale(key: string): boolean {
    const entry = this.cache.get(key);
    if (!entry) return true;

    const age = Date.now() - entry.timestamp;
    return age > entry.ttl;
  }

  clear(): void {
    this.cache.clear();
  }
}

// Usage in adapter
export class HuggingFaceAdapter {
  private cache = new HuggingFaceCache();

  async fetchData<T>(endpoint: string, cacheTTL?: number): Promise<T> {
    // Try cache first
    const cached = this.cache.get<T>(endpoint);
    if (cached) {
      console.log(`[Cache] Hit for ${endpoint}`);
      return cached;
    }

    // Fetch from Space
    console.log(`[HF] Fetching ${endpoint}...`);
    const data = await this.doFetch<T>(endpoint);

    // Cache result
    this.cache.set(endpoint, data, cacheTTL);

    return data;
  }

  private async doFetch<T>(endpoint: string): Promise<T> {
    const response = await fetch(`${this.config.baseUrl}${endpoint}`);
    return response.json();
  }
}
```

**Fix Option 4: Use Request Pooling**

```typescript
// src/services/adapters/huggingface.adapter.ts

export class HuggingFaceAdapter {
  private requestPool = new Map<string, Promise<any>>();

  async fetchData<T>(endpoint: string): Promise<T> {
    // If same request is in-flight, return that promise instead of creating new request
    if (this.requestPool.has(endpoint)) {
      console.log(`[Pool] Reusing in-flight request for ${endpoint}`);
      return this.requestPool.get(endpoint)!;
    }

    // Create new request
    const promise = this.doFetch<T>(endpoint)
      .finally(() => {
        this.requestPool.delete(endpoint);
      });

    this.requestPool.set(endpoint, promise);
    return promise;
  }

  private async doFetch<T>(endpoint: string): Promise<T> {
    const url = `${this.config.baseUrl}${endpoint}`;
    const response = await fetch(url);
    return response.json();
  }
}
```

---

### Issue 6: Authentication Required (401/403)

**Symptoms:**
- `401 Unauthorized`
- `403 Forbidden`
- Response: `{"error": "Authentication required"}`
- Error: `Invalid token` or `Expired credentials`

**Root Cause:**
Space requires authentication (API token or credentials) that isn't provided.

**Diagnosis:**

```bash
# Test without authentication
curl -s https://really-amin-datasourceforcryptocurrency.hf.space/api/prices | jq

# Test with different auth methods

# Method 1: Bearer token
curl -H "Authorization: Bearer YOUR_TOKEN_HERE" \
  https://really-amin-datasourceforcryptocurrency.hf.space/api/prices

# Method 2: API key in header
curl -H "X-API-Key: YOUR_KEY_HERE" \
  https://really-amin-datasourceforcryptocurrency.hf.space/api/prices

# Method 3: API key in query
curl "https://really-amin-datasourceforcryptocurrency.hf.space/api/prices?api_key=YOUR_KEY_HERE"

# Check response status and error details
curl -i https://really-amin-datasourceforcryptocurrency.hf.space/api/prices
```

**Fix Option 1: Add Authentication to Configuration**

```bash
# .env
VITE_HF_API_TOKEN=hf_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
VITE_HF_API_KEY=your-api-key-here
```

```typescript
// src/config/huggingface.ts
export const huggingfaceConfig = {
  baseUrl: 'https://really-amin-datasourceforcryptocurrency.hf.space',
  apiToken: import.meta.env.VITE_HF_API_TOKEN,
  apiKey: import.meta.env.VITE_HF_API_KEY,
};

// src/types/config.ts
export interface HuggingFaceConfig {
  baseUrl: string;
  timeout: number;
  apiToken?: string;  // For Bearer token auth
  apiKey?: string;    // For X-API-Key header
}
```

**Fix Option 2: Update Adapter to Include Auth Headers**

```typescript
// src/services/adapters/huggingface.adapter.ts

private getHeaders(): Record<string, string> {
  const headers: Record<string, string> = {
    'Content-Type': 'application/json',
    'Accept': 'application/json',
  };

  // Add authentication if configured
  if (this.config.apiToken) {
    headers['Authorization'] = `Bearer ${this.config.apiToken}`;
  }

  if (this.config.apiKey) {
    headers['X-API-Key'] = this.config.apiKey;
  }

  return headers;
}

async fetchData<T>(endpoint: string): Promise<T> {
  const url = `${this.config.baseUrl}${endpoint}`;

  try {
    const response = await fetch(url, {
      method: 'GET',
      headers: this.getHeaders(),
      signal: AbortSignal.timeout(this.config.timeout),
    });

    if (response.status === 401 || response.status === 403) {
      throw new Error('Authentication failed. Check your API token/key.');
    }

    if (!response.ok) {
      const error = await response.text();
      throw new Error(`HTTP ${response.status}: ${error}`);
    }

    return response.json();
  } catch (error) {
    console.error('[HF Auth Error]', error);
    throw error;
  }
}
```

**Fix Option 3: Get HuggingFace Token**

If Space requires HuggingFace credentials:

1. Visit: https://huggingface.co/settings/tokens
2. Click "New token"
3. Create token with "Read" access
4. Copy token to `.env`:
   ```env
   VITE_HF_API_TOKEN=hf_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
   ```

---

## πŸ§ͺ Testing Protocol

### Test Sequence

Follow these tests in order. **Stop at the first failure** and fix before continuing.

#### Test 1: Space Health Check

```bash
echo "πŸ” Test 1: Space Health Check"
curl -v https://really-amin-datasourceforcryptocurrency.hf.space/api/health

# βœ… Expected:
# HTTP/2 200 (or HTTP/1.1 200)
# Content-Type: application/json
# {"status": "healthy"}

# ❌ If fails:
# - HTTP 503: Space is building (wait 60 seconds)
# - HTTP 000 / Timeout: Space is sleeping (send request to wake it)
# - HTTP 404: Wrong endpoint (check endpoint mapping)
```

#### Test 2: Prices Endpoint

```bash
echo "πŸ” Test 2: Prices Endpoint"
curl -s "https://really-amin-datasourceforcryptocurrency.hf.space/api/prices?symbols=BTC,ETH" | jq '.'

# βœ… Expected: Returns array or object with price data

# ❌ If fails:
# - Empty response: Try adding limit parameter
# - null: Endpoint exists but no data
# - 404: Wrong endpoint path
```

#### Test 3: OHLCV Endpoint

```bash
echo "πŸ” Test 3: OHLCV Endpoint"
curl -s "https://really-amin-datasourceforcryptocurrency.hf.space/api/ohlcv?symbol=BTCUSDT&interval=1h&limit=10" | jq '.[:1]'

# βœ… Expected: OHLCV data with candle information

# ❌ If fails:
# - 404: Try different endpoint patterns
# - Wrong symbol format: Check symbol requirements (BTCUSDT vs BTC)
```

#### Test 4: Local Development (Vite Proxy)

```bash
echo "πŸ” Test 4: Local Development"

# Make sure .env is configured
if [ ! -f .env ]; then
    cp .env.example .env
fi

# Install dependencies
npm install

# Start dev server
npm run dev &
DEV_PID=$!

# Wait for server to start
sleep 5

# Test via proxy
echo "Testing via proxy (http://localhost:5173/api/hf/...)"
curl -s "http://localhost:5173/api/hf/api/health" | jq

# Stop dev server
kill $DEV_PID

# βœ… Expected: Same response as direct Space call

# ❌ If fails:
# - Connection refused: Dev server didn't start
# - 404: Proxy path incorrect
# - CORS error: Check vite.config.ts
```

#### Test 5: Browser Testing

```bash
echo "πŸ” Test 5: Browser Testing"

# 1. Start dev server
npm run dev

# 2. Open browser: http://localhost:5173

# 3. Open DevTools (F12)

# 4. Go to Network tab

# 5. Trigger data fetch (click buttons, load page, etc.)

# 6. Look for requests to /api/hf/...

# 7. Check response status
#    βœ… 200 = Success
#    ❌ 404 = Wrong endpoint
#    ❌ 0 (blocked) = CORS issue

# 8. Go to Console tab

# 9. Look for errors:
#    ❌ "Access to fetch blocked by CORS" β†’ Use Vite proxy
#    ❌ "Cannot read property 'symbol' of undefined" β†’ Data mapping issue
#    ❌ "Timeout" β†’ Increase timeout in config
```

### Complete Test Checklist

- [ ] Health check returns 200
- [ ] Prices endpoint returns data
- [ ] OHLCV endpoint returns data
- [ ] Vite proxy works locally
- [ ] No CORS errors in browser console
- [ ] Data renders correctly in UI
- [ ] No undefined values in UI
- [ ] Network requests complete < 30 seconds
- [ ] Application handles errors gracefully

---

## πŸ› Debugging Commands

### Debugging HuggingFace Integration

```bash
# Enable verbose logging
export DEBUG=*:huggingface*,*:adapter*

# Watch logs in real-time
npm run dev 2>&1 | grep -i "huggingface\|hf\|adapter"

# Log all fetch requests
cat > src/services/debug.ts << 'EOF'
// Intercept all fetch calls
const originalFetch = window.fetch;
window.fetch = function(...args) {
  const [resource] = args;
  console.log(`πŸ“‘ Fetch: ${resource}`);

  return originalFetch.apply(this, args as any)
    .then(response => {
      console.log(`πŸ“‘ Response: ${resource} β†’ ${response.status}`);
      return response.clone();
    })
    .catch(error => {
      console.error(`πŸ“‘ Error: ${resource} β†’`, error);
      throw error;
    });
};
EOF

# In your main component or app.tsx:
// Add this early in your app initialization
import './services/debug';
```

### Network Debugging

```bash
# Monitor network activity
curl -v https://really-amin-datasourceforcryptocurrency.hf.space/api/prices

# Show request headers only
curl -I https://really-amin-datasourceforcryptocurrency.hf.space/api/health

# Show response headers
curl -D - https://really-amin-datasourceforcryptocurrency.hf.space/api/health

# Test with custom headers
curl -H "Authorization: Bearer token" \
     -H "X-Custom-Header: value" \
     https://really-amin-datasourceforcryptocurrency.hf.space/api/prices

# Save full request/response to file
curl -v https://really-amin-datasourceforcryptocurrency.hf.space/api/health 2>&1 | tee debug.log
```

### Response Inspection

```bash
# Pretty print JSON response
curl -s https://really-amin-datasourceforcryptocurrency.hf.space/api/prices | jq '.'

# Show specific fields
curl -s https://really-amin-datasourceforcryptocurrency.hf.space/api/prices | jq '.[0] | keys'

# Count items
curl -s https://really-amin-datasourceforcryptocurrency.hf.space/api/prices | jq 'length'

# Filter by condition
curl -s https://really-amin-datasourceforcryptocurrency.hf.space/api/prices | jq '.[] | select(.symbol == "BTC")'

# Convert to CSV
curl -s https://really-amin-datasourceforcryptocurrency.hf.space/api/prices | jq -r '.[] | [.symbol, .price] | @csv'
```

### TypeScript/React Debugging

```typescript
// Add detailed logging to adapter
class HuggingFaceAdapter {
  async fetchData<T>(endpoint: string): Promise<T> {
    const url = `${this.baseUrl}${endpoint}`;

    console.group(`πŸ”΅ HF Fetch: ${endpoint}`);
    console.log('URL:', url);
    console.log('Headers:', this.getHeaders());
    console.log('Timeout:', this.config.timeout);
    console.timeStamp('start');

    try {
      const response = await fetch(url, {
        headers: this.getHeaders(),
      });

      const elapsed = performance.now() - performance.timing.navigationStart;
      console.log('Response status:', response.status);
      console.log('Time elapsed:', `${elapsed}ms`);

      const data = await response.json();
      console.log('Response data:', data);
      console.groupEnd();

      return data;
    } catch (error) {
      console.error('Error:', error);
      console.groupEnd();
      throw error;
    }
  }
}
```

### Performance Profiling

```bash
# Measure response time
time curl -s https://really-amin-datasourceforcryptocurrency.hf.space/api/prices > /dev/null

# Detailed timing breakdown
curl -w "
Time breakdown:
  DNS lookup: %{time_namelookup}s
  TCP connect: %{time_connect}s
  TLS handshake: %{time_appconnect}s
  Server processing: %{time_starttransfer}s
  Total: %{time_total}s
" -o /dev/null -s https://really-amin-datasourceforcryptocurrency.hf.space/api/prices

# Repeat tests and get average
for i in {1..5}; do
  echo "Request $i:"
  curl -w "Time: %{time_total}s\n" -o /dev/null -s https://really-amin-datasourceforcryptocurrency.hf.space/api/prices
done
```

---

## βš™οΈ Configuration Guide

### Environment Variables

Create `.env` file based on `.env.example`:

```bash
# Copy template
cp .env.example .env
```

### Available Configuration Options

```env
# Data Source Configuration
PRIMARY_DATA_SOURCE=huggingface          # Main data source: huggingface, coingecko, binance
FALLBACK_ENABLED=true                   # Enable fallback sources
FALLBACK_SOURCES=coingecko,coincap       # Comma-separated fallback sources

# HuggingFace Space Configuration
HF_SPACE_BASE_URL=https://really-amin-datasourceforcryptocurrency.hf.space
HF_REQUEST_TIMEOUT=30000                # Request timeout in milliseconds
HF_CACHE_TTL=300000                     # Cache time-to-live in milliseconds (5 minutes)
HF_API_TOKEN=                           # HuggingFace API token (if required)

# Development Configuration
VITE_DEV_SERVER_HOST=localhost
VITE_DEV_SERVER_PORT=5173
VITE_LOG_LEVEL=info                     # debug, info, warn, error

# Proxy Configuration (for development)
VITE_USE_PROXY=true                     # Use Vite proxy for API calls
VITE_PROXY_PATH=/api/hf                 # Proxy mount path
```

### Vite Configuration

File: `vite.config.ts`

```typescript
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'

export default defineConfig({
  plugins: [react()],

  server: {
    host: 'localhost',
    port: 5173,

    proxy: {
      '/api/hf': {
        target: 'https://really-amin-datasourceforcryptocurrency.hf.space',
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/api\/hf/, ''),
        configure: (proxy, options) => {
          proxy.on('error', (err, req, res) => {
            console.error('Proxy error:', err);
          });
          proxy.on('proxyReq', (proxyReq, req, res) => {
            console.log('β†’ Proxying:', req.method, req.url);
          });
          proxy.on('proxyRes', (proxyRes, req, res) => {
            console.log('← Response:', proxyRes.statusCode);
          });
        }
      }
    }
  },

  build: {
    outDir: 'dist',
    sourcemap: true,
  }
})
```

### TypeScript Configuration

File: `tsconfig.json`

```json
{
  "compilerOptions": {
    "target": "ES2020",
    "useDefineForClassFields": true,
    "lib": ["ES2020", "DOM", "DOM.Iterable"],
    "module": "ESNext",
    "skipLibCheck": true,
    "esModuleInterop": true,
    "strict": true,
    "resolveJsonModule": true,
    "declaration": true,
    "declarationMap": true,
    "sourceMap": true,
    "allowJs": false,
    "baseUrl": ".",
    "paths": {
      "@/*": ["src/*"],
      "@/services/*": ["src/services/*"],
      "@/components/*": ["src/components/*"],
      "@/types/*": ["src/types/*"]
    }
  }
}
```

---

## 🌳 Troubleshooting Decision Tree

Start here when you encounter issues:

```
β”Œβ”€ START: Application not working
β”‚
β”œβ”€ Step 1: Can you reach the Space?
β”‚  β”‚
β”‚  β”œβ”€ NO (timeout, connection refused)
β”‚  β”‚  └─ Issue 1: Space is sleeping β†’ Wake it up
β”‚  β”‚
β”‚  └─ YES (200 OK)
β”‚     β”‚
β”‚     └─ Step 2: Are you getting the correct endpoints?
β”‚        β”‚
β”‚        β”œβ”€ NO (404 Not Found)
β”‚        β”‚  └─ Issue 2: Wrong endpoints β†’ Update adapter
β”‚        β”‚
β”‚        └─ YES (200 OK)
β”‚           β”‚
β”‚           └─ Step 3: Is the data in the correct format?
β”‚              β”‚
β”‚              β”œβ”€ NO (undefined values, type errors)
β”‚              β”‚  └─ Issue 3: Response format mismatch β†’ Update mapping
β”‚              β”‚
β”‚              └─ YES (correct data types)
β”‚                 β”‚
β”‚                 └─ Step 4: Does the browser show CORS errors?
β”‚                    β”‚
β”‚                    β”œβ”€ YES (Access blocked by CORS)
β”‚                    β”‚  └─ Issue 4: CORS errors β†’ Add Vite proxy
β”‚                    β”‚
β”‚                    └─ NO (no CORS errors)
β”‚                       β”‚
β”‚                       └─ Step 5: Are requests timing out?
β”‚                          β”‚
β”‚                          β”œβ”€ YES (AbortError timeout)
β”‚                          β”‚  └─ Issue 5: Timeout β†’ Increase timeout or use caching
β”‚                          β”‚
β”‚                          └─ NO (requests complete)
β”‚                             β”‚
β”‚                             └─ Step 6: Check authentication
β”‚                                β”‚
β”‚                                β”œβ”€ 401/403 errors
β”‚                                β”‚  └─ Issue 6: Auth required β†’ Add token/key
β”‚                                β”‚
β”‚                                └─ βœ… WORKING!
```

**Quick Reference:**
- Space not responding β†’ Check Space status, wait 60 seconds
- Getting 404 β†’ Update endpoint paths in adapter
- Data undefined β†’ Update field name mappings
- CORS errors β†’ Enable Vite proxy
- Timeouts β†’ Increase timeout or implement caching
- 401/403 β†’ Add API token/key to config

---

## ❓ FAQ

### Q: How do I know which version of the Space is deployed?

```bash
# Check Space's version endpoint (if available)
curl -s https://really-amin-datasourceforcryptocurrency.hf.space/api/version

# Or check the Space's README on HuggingFace
# Visit: https://huggingface.co/spaces/Really-amin/Datasourceforcryptocurrency

# Or check git log if you have access
cd hf-data-engine
git log --oneline | head -5
```

### Q: Can I use this application without HuggingFace?

Yes! Configure fallback data sources:

```env
PRIMARY_DATA_SOURCE=coingecko
FALLBACK_ENABLED=true
FALLBACK_SOURCES=coincap,binance
```

### Q: What if HuggingFace Space goes down permanently?

1. Deploy your own instance of `hf-data-engine`
2. Update `HF_SPACE_BASE_URL` in `.env`
3. Or switch to fallback sources permanently

### Q: How do I cache data for offline use?

```typescript
// src/services/storage/localStorage.cache.ts

export class LocalStorageCache {
  static set<T>(key: string, data: T): void {
    localStorage.setItem(key, JSON.stringify({
      data,
      timestamp: Date.now(),
    }));
  }

  static get<T>(key: string, maxAge?: number): T | null {
    const stored = localStorage.getItem(key);
    if (!stored) return null;

    const { data, timestamp } = JSON.parse(stored);

    if (maxAge && Date.now() - timestamp > maxAge) {
      localStorage.removeItem(key);
      return null;
    }

    return data;
  }
}
```

### Q: How do I monitor HuggingFace Space uptime?

Use a monitoring service or cron job:

```bash
# Create uptime.sh
#!/bin/bash
TIMESTAMP=$(date -u +"%Y-%m-%dT%H:%M:%SZ")
STATUS=$(curl -s -o /dev/null -w "%{http_code}" https://really-amin-datasourceforcryptocurrency.hf.space/api/health)
echo "$TIMESTAMP,HuggingFace Space,$STATUS" >> uptime.log

# Add to crontab
*/5 * * * * /path/to/uptime.sh
```

### Q: Can I contribute improvements to the HuggingFace Space?

Yes! The space is open source:

1. Fork the repository
2. Make improvements
3. Submit a pull request
4. Visit: https://huggingface.co/spaces/Really-amin/Datasourceforcryptocurrency

### Q: What are the rate limits?

From the Space documentation:
- `/api/prices`: 120 requests/minute
- `/api/ohlcv`: 60 requests/minute
- `/api/sentiment`: 30 requests/minute
- `/api/health`: Unlimited

Implement rate limiting in your client:

```typescript
// src/services/rateLimit.ts

export class RateLimiter {
  private timestamps: number[] = [];

  constructor(private maxRequests: number, private windowMs: number) {}

  canRequest(): boolean {
    const now = Date.now();

    // Remove old timestamps outside window
    this.timestamps = this.timestamps.filter(ts => now - ts < this.windowMs);

    // Check if under limit
    if (this.timestamps.length < this.maxRequests) {
      this.timestamps.push(now);
      return true;
    }

    return false;
  }
}

// Usage
const limiter = new RateLimiter(100, 60000); // 100 req/min

if (limiter.canRequest()) {
  // Make request
} else {
  // Wait or queue request
}
```

### Q: How do I debug issues in production?

1. Check browser console for errors
2. Check Network tab for failed requests
3. Review server logs
4. Use error tracking service (Sentry, LogRocket, etc.)

```typescript
// Error tracking integration
import * as Sentry from "@sentry/react";

Sentry.init({
  dsn: "your-sentry-dsn",
  environment: import.meta.env.MODE,
  tracesSampleRate: 0.1,
});

try {
  // Your code
} catch (error) {
  Sentry.captureException(error);
}
```

---

## πŸ“ž Support

- **HuggingFace Space:** https://huggingface.co/spaces/Really-amin/Datasourceforcryptocurrency
- **GitHub Issues:** Report bugs and request features
- **Documentation:** See README.md and other docs

---

**Last Updated:** 2025-11-15
**Version:** 2.0
**Maintained by:** Crypto Data Aggregator Team