Repository navigation
Expand file tree
/
Copy pathscript.js
More file actions
5388 lines (4699 loc) · 244 KB
/
Copy pathscript.js
File metadata and controls
5388 lines (4699 loc) · 244 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
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
// Utility function: Format date to readable format (e.g., "Jan 15, 2024")
function formatDate(dateString) {
if (!dateString) return 'Unknown Date';
try {
// Handle ISO format (YYYY-MM-DD) or timestamp
const date = new Date(dateString);
// Check if date is valid
if (isNaN(date.getTime())) {
return dateString; // Return original if invalid
}
// Format as "Month Day, Year" (e.g., "Jan 15, 2024")
const options = { year: 'numeric', month: 'short', day: 'numeric' };
return date.toLocaleDateString('en-US', options);
} catch (error) {
// If parsing fails, return original string
return dateString;
}
}
// Utility function: fetch weather for Troy, NY (latitude, longitude)
function fetchTroyWeather() {
// Coordinates for Troy, NY (approx)
const latitude = 42.7284;
const longitude = -73.6918;
// Build the Open-Meteo API URL shold lwk wrk with any api.
// im finna request current + hourly temperature and wind speed for the next day.
const url = `https://api.open-meteo.com/v1/forecast?latitude=${latitude}&longitude=${longitude}` +
`&hourly=temperature_2m,wind_speed_10m¤t_weather=true`;
// returns api response
return fetch(url)
.then(response => {
if (!response.ok) {
throw new Error(`Weather API returned status ${response.status}`);
}
return response.json();
});
}
// Data objects for League data (mutable, ready for API integration)
let leagueData = {
currentRank: null, // Will hold current rank from API
pastSeasonRanks: [],
mostPlayedChampions: [],
quests: [], // Generated quests based on rank
matches: [], // Match history with champ/role data
playerLevel: {
level: 1, // Current player level
totalXP: 0, // Total XP earned
xpForNextLevel: 100 // XP needed to reach next level
}
};
// Hardcoded API key that doesn't expire
const HARDCODED_API_KEY = 'RGAPI-85f2a440-debe-4931-bd7f-cfb521126bdd';
// User credentials storage
let userCredentials = {
apiKey: HARDCODED_API_KEY, // Hardcoded API key (doesn't expire)
gameName: null,
tagLine: null,
region: null
};
// Data loading state - track if data has been loaded and when
let dataLoadState = {
isLoaded: false,
isLoading: false,
lastLoadTime: null,
loadPromise: null
};
// Map region codes to routing regions (for APIs that need routing regions)
function getRoutingRegion(regionCode) {
const routingMap = {
// Americas
'na1': 'americas',
'br1': 'americas',
'la1': 'americas',
'la2': 'americas',
// Europe & Middle East
'euw1': 'europe',
'eun1': 'europe',
'tr1': 'europe',
'ru': 'europe',
'me1': 'europe',
// Asia Pacific
'kr': 'asia',
'jp1': 'asia',
'tw2': 'asia',
'vn2': 'asia',
'ph2': 'asia',
'sg2': 'asia',
'th2': 'asia',
'id1': 'asia',
// Oceania
'oc1': 'asia' // Oceania typically uses Asia routing
};
// If it's already a routing region, return as-is
if (['americas', 'europe', 'asia'].includes(regionCode.toLowerCase())) {
return regionCode.toLowerCase();
}
return routingMap[regionCode] || 'americas'; // Default fallback
}
// ✅ Fetch player stats from AWS API Gateway (CrystalJSScore Lambda)
// Matches your exact API structure
async function getPlayerStats(apiKey, name, tag, region) {
const ENDPOINT = "https://q9nbniuo24.execute-api.us-east-2.amazonaws.com/default/CrystalJSScore1-1";
// Add timeout (30 seconds)
const timeout = 30000;
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), timeout);
try {
console.log("🔄 Fetching player stats from Lambda...");
console.log("🔍 ========== DIAGNOSTIC VALIDATION ==========");
// Process and validate each parameter
const processedApiKey = (apiKey && apiKey.trim()) ? apiKey.trim() : '';
const processedName = (name && name.trim()) ? name.trim() : '';
const processedTag = (tag && tag.trim()) ? tag.trim() : '';
const processedRegion = (region && region.trim()) ? region.trim() : '';
// 1. API KEY VALIDATION
console.log("🔑 API KEY DIAGNOSTICS:");
console.log(" - Raw value:", apiKey ? `"${apiKey.substring(0, 10)}..." (${apiKey.length} chars)` : '(empty)');
console.log(" - Processed value:", processedApiKey ? `"${processedApiKey.substring(0, 10)}..." (${processedApiKey.length} chars)` : '(empty)');
console.log(" - Format check:", processedApiKey.startsWith('RGAPI-') ? '✅ Starts with RGAPI-' : '❌ Does NOT start with RGAPI-');
console.log(" - Length check:", processedApiKey.length >= 20 ? `✅ Length OK (${processedApiKey.length})` : `❌ Too short (${processedApiKey.length}, expected ≥20)`);
// 2. GAME NAME VALIDATION
console.log("👤 GAME NAME DIAGNOSTICS:");
console.log(" - Raw value:", name ? `"${name}" (${name.length} chars)` : '(empty)');
console.log(" - Processed value:", processedName ? `"${processedName}" (${processedName.length} chars)` : '(empty)');
console.log(" - Has spaces:", processedName.includes(' ') ? `✅ Contains spaces: "${processedName}"` : 'No spaces');
console.log(" - Length check:", processedName.length >= 3 && processedName.length <= 16 ? `✅ Length OK (${processedName.length})` : `⚠️ Length: ${processedName.length} (expected 3-16)`);
console.log(" - Special chars:", /[^a-zA-Z0-9\s]/.test(processedName) ? `⚠️ Contains special chars` : '✅ No special chars');
// 3. TAG LINE VALIDATION
console.log("🏷️ TAG LINE DIAGNOSTICS:");
console.log(" - Raw value:", tag ? `"${tag}" (${tag.length} chars)` : '(empty)');
console.log(" - Processed value:", processedTag ? `"${processedTag}" (${processedTag.length} chars)` : '(empty)');
console.log(" - Length check:", processedTag.length >= 2 && processedTag.length <= 5 ? `✅ Length OK (${processedTag.length})` : `⚠️ Length: ${processedTag.length} (expected 2-5)`);
console.log(" - Format check:", /^[A-Z0-9]+$/.test(processedTag.toUpperCase()) ? '✅ Valid format (alphanumeric)' : '⚠️ May contain invalid characters');
// 4. REGION VALIDATION
console.log("🌍 REGION DIAGNOSTICS:");
console.log(" - Raw value:", region ? `"${region}"` : '(empty)');
console.log(" - Processed value:", processedRegion ? `"${processedRegion}"` : '(empty)');
// Define valid routing regions (accessible throughout function)
const validRegions = ['americas', 'europe', 'asia'];
const processedRegionLower = processedRegion.toLowerCase();
console.log(" - Valid region check:", validRegions.includes(processedRegionLower) ? `✅ Valid routing region: "${processedRegion}"` : `❌ INVALID routing region: "${processedRegion}" (expected one of: ${validRegions.join(', ')})`);
if (!validRegions.includes(processedRegionLower) && processedRegion) {
console.error(" ❌ REGION MISMATCH! The region you entered doesn't match any valid routing region.");
console.error(" Please select: Americas, Europe, or Asia from the dropdown.");
}
console.log("🔍 ==========================================");
// Build request payload - Lambda requires all fields including api_key
// Use routing region directly (americas, europe, asia)
const routingRegion = getRoutingRegion(processedRegion.toLowerCase());
const requestPayload = {
api_key: processedApiKey,
game_name: processedName,
tag_line: processedTag,
region: routingRegion, // Use routing region (americas, europe, asia)
};
// Validate all required fields are present (non-empty)
const validationErrors = [];
if (!requestPayload.api_key) {
validationErrors.push('API key is empty');
} else if (!requestPayload.api_key.startsWith('RGAPI-')) {
validationErrors.push('API key format invalid (should start with RGAPI-)');
}
if (!requestPayload.game_name) {
validationErrors.push('game_name is empty');
}
if (!requestPayload.tag_line) {
validationErrors.push('tag_line is empty');
}
if (!requestPayload.region) {
validationErrors.push('region is empty');
} else if (!validRegions.includes(requestPayload.region)) {
validationErrors.push(`region "${requestPayload.region}" is not a valid Riot API region code`);
}
if (validationErrors.length > 0) {
console.error("❌ VALIDATION ERRORS:", validationErrors);
throw new Error(`Validation failed:\n${validationErrors.map(e => ` • ${e}`).join('\n')}`);
}
// Log what we're sending (mask API key for security)
console.log("📤 Request payload:", {
api_key: requestPayload.api_key ? '***' : '(empty string)',
game_name: requestPayload.game_name,
tag_line: requestPayload.tag_line,
region: requestPayload.region
});
// Log the actual JSON to verify structure
const jsonPayload = JSON.stringify(requestPayload);
console.log("📤 JSON payload being sent:", jsonPayload);
console.log("📤 Payload length:", jsonPayload.length, "bytes");
const response = await fetch(ENDPOINT, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: jsonPayload, // Use the pre-stringified JSON
signal: controller.signal
});
clearTimeout(timeoutId);
if (!response.ok) {
const errText = await response.text();
console.error("❌ API Error Response:", errText);
console.error("❌ Request payload that failed:", {
api_key: requestPayload.api_key ? '***' : '(empty)',
game_name: requestPayload.game_name,
tag_line: requestPayload.tag_line,
region: requestPayload.region
});
console.error("❌ Full JSON payload that was sent:", jsonPayload);
console.error("❌ Response status:", response.status);
// Parse error for better user messaging
let errorMessage = `HTTP ${response.status}: ${errText}`;
let diagnosticInfo = '';
try {
const errorObj = JSON.parse(errText);
if (errorObj.error) {
errorMessage = errorObj.error;
// Check if it's a 403 error (API key issue)
if (response.status === 403 || errorMessage.includes('403') || errorMessage.includes('Forbidden')) {
console.error("🔍 ========== 403 ERROR DIAGNOSTICS ==========");
console.error(" A 403 Forbidden error from Riot API typically means:");
console.error(" 1. API KEY ISSUE (most common):");
console.error(" - API key is invalid or expired");
console.error(" - API key doesn't have required permissions");
console.error(" - API key format is incorrect");
console.error(" 📋 Current API key check:");
console.error(" - Format:", requestPayload.api_key.startsWith('RGAPI-') ? '✅ Correct' : '❌ Wrong format');
console.error(" - Length:", requestPayload.api_key.length >= 20 ? `✅ OK (${requestPayload.api_key.length})` : `❌ Too short (${requestPayload.api_key.length})`);
console.error(" 2. ACCOUNT ISSUE:");
console.error(" - Game name + tag line don't match any account");
console.error(" - Account doesn't exist in the specified region");
console.error(" - Account is private or banned");
console.error(" 📋 Current account check:");
console.error(" - Game Name:", `"${requestPayload.game_name}"`);
console.error(" - Tag Line:", `"${requestPayload.tag_line}"`);
console.error(" - Combined:", `"${requestPayload.game_name}#${requestPayload.tag_line}"`);
console.error(" 3. REGION MISMATCH:");
console.error(" - Account exists but in a different routing region");
console.error(" - Routing region is incorrect (should be: americas, europe, or asia)");
console.error(" 📋 Current region check:");
console.error(" - Region:", `"${requestPayload.region}"`);
console.error(" - Valid:", validRegions.includes(requestPayload.region.toLowerCase()) ? '✅ Yes' : '❌ No');
console.error("🔍 ==========================================");
diagnosticInfo = '\n\n🔍 DIAGNOSTIC SUMMARY:\n';
diagnosticInfo += `API Key: ${requestPayload.api_key.startsWith('RGAPI-') && requestPayload.api_key.length >= 20 ? '✅ Format looks OK' : '❌ Format or length issue'}\n`;
diagnosticInfo += `Game Name: "${requestPayload.game_name}" (${requestPayload.game_name.length} chars)\n`;
diagnosticInfo += `Tag Line: "${requestPayload.tag_line}" (${requestPayload.tag_line.length} chars)\n`;
diagnosticInfo += `Region: "${requestPayload.region}" ${validRegions.includes(requestPayload.region.toLowerCase()) ? '✅' : '❌ INVALID (must be: americas, europe, or asia)'}\n`;
diagnosticInfo += `\n⚠️ MOST COMMON CAUSE: API KEY EXPIRED\n`;
diagnosticInfo += `Riot API keys expire after 24 hours. If this worked before, your key likely expired.\n\n`;
diagnosticInfo += `💡 TROUBLESHOOTING (in order of likelihood):\n`;
diagnosticInfo += `1. 🔑 API KEY EXPIRED (most common) - Get a new key from https://developer.riotgames.com/\n`;
diagnosticInfo += ` • Log in to Riot Developer Portal\n`;
diagnosticInfo += ` • Go to "API Keys" section\n`;
diagnosticInfo += ` • Generate a new key (starts with RGAPI-)\n`;
diagnosticInfo += ` • Copy and paste it into the API Key field above\n`;
diagnosticInfo += `2. Check if "${requestPayload.game_name}#${requestPayload.tag_line}" exists in routing region "${requestPayload.region}"\n`;
diagnosticInfo += `3. Try a different routing region (americas, europe, or asia) if the account might be in another region\n`;
diagnosticInfo += `4. Verify the account is not private or banned`;
errorMessage = 'Riot API returned 403 Forbidden.' + diagnosticInfo;
} else if (response.status === 400) {
console.error("🔍 400 Bad Request - Likely a parameter format issue");
diagnosticInfo = '\n\n🔍 This usually means:\n';
diagnosticInfo += '• One or more parameters are in the wrong format\n';
diagnosticInfo += '• Missing required fields\n';
diagnosticInfo += '• Invalid region code\n';
errorMessage += diagnosticInfo;
} else if (response.status === 404 || response.status === 500) {
// Check if it's a 404 account not found error
if (errorMessage.includes('404') || errorMessage.includes('Account lookup failed')) {
console.error("🔍 ========== 404 ACCOUNT NOT FOUND DIAGNOSTICS ==========");
console.error(" The account could not be found. This usually means:");
console.error(" 1. ACCOUNT NAME/TAG MISMATCH:");
console.error(" - The game name and tag line don't match any account");
console.error(" - Account name is case-sensitive (check capitalization)");
console.error(" - Account might have been renamed or deleted");
console.error(" 📋 Current account check:");
console.error(" - Game Name:", `"${requestPayload.game_name}"`);
console.error(" - Tag Line:", `"${requestPayload.tag_line}"`);
console.error(" - Combined:", `"${requestPayload.game_name}#${requestPayload.tag_line}"`);
console.error(" 2. REGION MISMATCH:");
console.error(" - Account exists but in a different region");
console.error(" - Try: americas, europe, or asia");
console.error(" 📋 Current region check:");
console.error(" - Region:", `"${requestPayload.region}"`);
console.error("🔍 ==========================================");
diagnosticInfo = '\n\n🔍 ACCOUNT NOT FOUND - Troubleshooting:\n';
diagnosticInfo += `1. Verify the account "${requestPayload.game_name}#${requestPayload.tag_line}" exists\n`;
diagnosticInfo += ` • Check the exact spelling and capitalization\n`;
diagnosticInfo += ` • Riot account names are case-sensitive\n`;
diagnosticInfo += ` • Make sure there are no extra spaces before/after the name\n`;
diagnosticInfo += `2. Try a different region:\n`;
diagnosticInfo += ` • Current region: "${requestPayload.region}"\n`;
diagnosticInfo += ` • Try: americas, europe, or asia\n`;
diagnosticInfo += `3. Verify the account is active and not banned\n`;
diagnosticInfo += `4. Check if the account name has special characters that need to be entered exactly\n`;
errorMessage = `Account not found: "${requestPayload.game_name}#${requestPayload.tag_line}"` + diagnosticInfo;
}
}
}
} catch (e) {
// If error text isn't JSON, use it as-is
}
throw new Error(errorMessage);
}
const data = await response.json();
console.log("✅ API Response received:", data);
console.log("📊 Full API Response structure:", JSON.stringify(data, null, 2));
return data;
} catch (err) {
clearTimeout(timeoutId);
if (err.name === 'AbortError') {
throw new Error('Request timed out. The Lambda function may be experiencing cold start delays. Please try again.');
}
console.error("❌ Error fetching player stats:", err);
throw err;
}
}
// ✅ Fetch quests from AWS Lambda
// Matches your exact API structure - no api_key needed
async function getQuests(gameName, tagLine, region) {
const ENDPOINT = "https://03femdw9g5.execute-api.us-east-1.amazonaws.com/default/quests";
// Convert region code to routing region if needed
const routingRegion = getRoutingRegion(region);
// Add timeout (30 seconds)
const timeout = 30000;
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), timeout);
try {
console.log("🔄 Fetching quests from Lambda...");
console.log("📤 Request payload:", { game_name: gameName, tag_line: tagLine, region: routingRegion });
const response = await fetch(ENDPOINT, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
game_name: gameName,
tag_line: tagLine,
region: routingRegion, // Use routing region for quests API
}),
signal: controller.signal
});
clearTimeout(timeoutId);
if (!response.ok) {
const errText = await response.text();
console.error("❌ Quests API Error Response:", errText);
throw new Error(`HTTP ${response.status}: ${errText}`);
}
const data = await response.json();
console.log("✅ Quests API Response received:", data);
console.log("📊 Full Quests Response:", JSON.stringify(data, null, 2));
return data;
} catch (err) {
clearTimeout(timeoutId);
if (err.name === 'AbortError') {
throw new Error('Quest request timed out. Please try again.');
}
console.error("❌ Error fetching quests:", err);
throw err;
}
}
// ✅ Fetch AI-generated feedback from AWS Lambda
// Generates roast and compliment feedback for matches using AI
async function getAIFeedback(player, matchSummaries) {
// TODO: Replace this URL with your actual Lambda feedback endpoint after deployment
// The endpoint should be your API Gateway URL for the feedback Lambda function
const ENDPOINT = "https://xewn6ahmh9.execute-api.us-east-1.amazonaws.com/default/quests";
// Add timeout (30 seconds - AI calls can take time)
const timeout = 30000;
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), timeout);
try {
console.log("🤖 Fetching AI feedback from Lambda...");
console.log("📊 Matches to analyze:", matchSummaries.length);
// Log champion info for each match being sent
matchSummaries.forEach((match, index) => {
console.log(` Match ${index + 1}: Champion: ${match.champion}, Role: ${match.role}, KDA: ${match.kills}/${match.deaths}/${match.assists}`);
});
// Get region from user credentials
const region = userCredentials.region || 'americas';
const routingRegion = getRoutingRegion(region);
// Prepare the request payload matching the Lambda function's expected input
// The Lambda expects game_name, tag_line, and region at the top level
const gameName = player.gameName || player.game_name || userCredentials.gameName || '';
const tagLine = player.tagLine || player.tag_line || userCredentials.tagLine || '';
// CRITICAL: Ensure we're only analyzing ONE match at a time
// If multiple matches are sent, the Lambda might get confused
const singleMatch = matchSummaries.length === 1 ? matchSummaries[0] : null;
if (!singleMatch) {
throw new Error(`Expected exactly 1 match, but received ${matchSummaries.length} matches`);
}
// Extract champion and role from the SINGLE match being analyzed
const targetChampion = singleMatch.champion;
const targetRole = singleMatch.role;
const targetKDA = `${singleMatch.kills}/${singleMatch.deaths}/${singleMatch.assists}`;
console.log(`🎯 TARGET MATCH FOR FEEDBACK:`);
console.log(` Champion: ${targetChampion}`);
console.log(` Role: ${targetRole}`);
console.log(` KDA: ${targetKDA}`);
console.log(` CS: ${singleMatch.cs}`);
console.log(` Damage: ${singleMatch.damage}`);
console.log(` Gold: ${singleMatch.gold}`);
// Build request payload with explicit single match focus
// CRITICAL: Add explicit instruction to ONLY analyze the match we send
const requestPayload = {
game_name: gameName,
tag_line: tagLine,
region: routingRegion,
// Explicitly mark this as a single match analysis
singleMatch: true,
targetChampion: targetChampion,
targetRole: targetRole,
// CRITICAL INSTRUCTION: Only analyze the matchSummaries we send, ignore any other data
instruction: `IMPORTANT: Analyze ONLY the single match in matchSummaries array. The champion is ${targetChampion} playing ${targetRole}. Ignore any other match data. Generate feedback specifically for this ${targetChampion} ${targetRole} game only.`,
player: {
puuid: player.puuid || '',
gameName: gameName,
tagLine: tagLine
},
// Send ONLY the single match being analyzed - Lambda MUST use this, not quests data
matchSummaries: [singleMatch],
// Add a flag to tell Lambda to ignore quests data
ignoreQuestsData: true,
useOnlyProvidedMatches: true,
feedback: {
roast: "",
compliment: ""
}
};
console.log("📤 Sending request to Lambda:", {
game_name: gameName,
tag_line: tagLine,
region: routingRegion,
matchCount: 1, // Always 1 for single match analysis
targetChampion: targetChampion,
targetRole: targetRole,
singleMatch: true
});
// Log the exact payload being sent
console.log("📋 Full payload being sent:", JSON.stringify(requestPayload, null, 2));
const response = await fetch(ENDPOINT, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(requestPayload),
signal: controller.signal
});
clearTimeout(timeoutId);
if (!response.ok) {
const errorText = await response.text();
console.error("❌ Lambda Error Response:", errorText);
let errorMessage = `HTTP ${response.status}: ${errorText}`;
try {
const errorJson = JSON.parse(errorText);
errorMessage = errorJson.error || errorMessage;
} catch {
// Not JSON, use text as-is
}
throw new Error(errorMessage);
}
// Try to parse JSON response
const contentType = response.headers.get('content-type');
let data;
if (contentType && contentType.includes('application/json')) {
data = await response.json();
} else {
const text = await response.text();
// Try to parse as JSON even if content-type is wrong
try {
data = JSON.parse(text);
} catch {
throw new Error(`Invalid response format: ${text.substring(0, 100)}`);
}
}
console.log("✅ AI Feedback received:", data);
console.log("📋 Response structure:", {
hasFeedback: !!data.feedback,
hasRoast: !!data.roast,
hasCompliment: !!data.compliment,
hasContent: !!data.content,
contentType: data.content ? typeof data.content : 'none',
matchSummariesInResponse: data.matchSummaries ? data.matchSummaries.length : 0
});
// WARNING: If Lambda returns multiple matches, it's ignoring our single match request
if (data.matchSummaries && data.matchSummaries.length > 1) {
console.error("⚠️ WARNING: Lambda returned", data.matchSummaries.length, "matches but we only sent 1!");
console.error(" This means Lambda is using quests data instead of our single match.");
console.error(" Champions in response:", data.matchSummaries.map(m => m.champion).join(", "));
console.error(" We requested feedback for:", targetChampion);
}
// Extract feedback from response
// Handle different possible response structures
// Case 1: Direct feedback object
if (data.feedback && typeof data.feedback === 'object') {
// Check if both roast and compliment are already parsed
if (data.feedback.roast && data.feedback.compliment &&
typeof data.feedback.roast === 'string' &&
typeof data.feedback.compliment === 'string' &&
!data.feedback.compliment.includes('"content"')) {
console.log("✅ Found feedback in data.feedback (already parsed)");
return data.feedback; // { roast: "...", compliment: "..." }
}
// If compliment is a Claude API response string, parse it
if (data.feedback.compliment && typeof data.feedback.compliment === 'string' &&
data.feedback.compliment.includes('"content"')) {
console.log("✅ Found feedback object with Claude API response in compliment, parsing...");
try {
// Try to parse the compliment string - it might be truncated or malformed
let parsedCompliment;
try {
parsedCompliment = JSON.parse(data.feedback.compliment);
} catch (parseError) {
console.warn("⚠️ First parse attempt failed, trying to fix JSON...");
// Try to extract just the text content if JSON is malformed
const textMatch = data.feedback.compliment.match(/"text"\s*:\s*"([^"]*(?:\\.[^"]*)*)"/);
if (textMatch && textMatch[1]) {
// Unescape the JSON string
const unescapedText = textMatch[1].replace(/\\"/g, '"').replace(/\\n/g, '\n').replace(/\\\\/g, '\\');
try {
const innerParsed = JSON.parse(unescapedText);
return {
roast: data.feedback.roast || innerParsed.roast || "Parse Error",
compliment: innerParsed.compliment || "Parse Error"
};
} catch (innerError) {
console.error("❌ Error parsing inner JSON:", innerError);
throw parseError; // Re-throw original error
}
}
throw parseError; // Re-throw if we can't fix it
}
if (parsedCompliment.content && Array.isArray(parsedCompliment.content)) {
const textContent = parsedCompliment.content.find(c => c.type === 'text' && c.text);
if (textContent && textContent.text) {
try {
const innerParsed = JSON.parse(textContent.text);
return {
roast: data.feedback.roast || innerParsed.roast || "Parse Error",
compliment: innerParsed.compliment || "Parse Error"
};
} catch (innerError) {
console.error("❌ Error parsing inner text JSON:", innerError);
// If inner JSON is malformed, try to extract roast/compliment directly from text
const text = textContent.text;
const roastMatch = text.match(/"roast"\s*:\s*"([^"]*(?:\\.[^"]*)*)"/);
const complimentMatch = text.match(/"compliment"\s*:\s*"([^"]*(?:\\.[^"]*)*)"/);
if (roastMatch || complimentMatch) {
return {
roast: roastMatch ? roastMatch[1].replace(/\\"/g, '"').replace(/\\n/g, '\n') : (data.feedback.roast || "Parse Error"),
compliment: complimentMatch ? complimentMatch[1].replace(/\\"/g, '"').replace(/\\n/g, '\n') : "Parse Error"
};
}
}
}
}
} catch (e) {
console.error("❌ Error parsing feedback.compliment:", e);
console.error(" Compliment string length:", data.feedback.compliment?.length);
console.error(" First 500 chars:", data.feedback.compliment?.substring(0, 500));
}
}
// If roast is "Parse Error" or similar, try to get it from elsewhere
if (data.feedback.roast === "Parse Error" || !data.feedback.roast) {
console.log("⚠️ Roast is missing or 'Parse Error', checking other sources...");
}
}
// Case 2: Direct roast/compliment at top level
if (data.roast && data.compliment) {
console.log("✅ Found roast/compliment at top level");
return { roast: data.roast, compliment: data.compliment };
}
// Case 3: Claude API response structure (content array with text)
if (data.content && Array.isArray(data.content)) {
console.log("✅ Found Claude API response structure");
try {
// Find the text content
const textContent = data.content.find(c => c.type === 'text' && c.text);
if (textContent && textContent.text) {
console.log("📝 Found text content, parsing JSON...");
// The text is a JSON string, parse it
const parsedText = JSON.parse(textContent.text);
if (parsedText.roast && parsedText.compliment) {
console.log("✅ Successfully extracted roast and compliment from Claude response");
return {
roast: parsedText.roast,
compliment: parsedText.compliment
};
} else if (parsedText.feedback) {
// Sometimes it's nested in feedback
return parsedText.feedback;
}
}
} catch (e) {
console.error("❌ Error parsing Claude API response:", e);
console.error(" Text content:", textContent?.text?.substring(0, 200));
}
}
// Case 4: Feedback is a string that needs parsing
if (typeof data.feedback === 'string') {
console.log("✅ Found feedback as string, parsing...");
try {
const parsed = JSON.parse(data.feedback);
if (parsed.roast && parsed.compliment) {
return parsed;
} else if (parsed.feedback) {
return parsed.feedback;
}
} catch (e) {
console.error("❌ Error parsing feedback string:", e);
}
}
// Case 5: Compliment is a string (like in the user's example)
if (data.compliment && typeof data.compliment === 'string' && data.compliment.includes('"content"')) {
console.log("✅ Found compliment as Claude API response string, parsing...");
try {
const parsedCompliment = JSON.parse(data.compliment);
if (parsedCompliment.content && Array.isArray(parsedCompliment.content)) {
const textContent = parsedCompliment.content.find(c => c.type === 'text' && c.text);
if (textContent && textContent.text) {
const innerParsed = JSON.parse(textContent.text);
return {
roast: innerParsed.roast || data.roast || "Parse Error",
compliment: innerParsed.compliment || "Parse Error"
};
}
}
} catch (e) {
console.error("❌ Error parsing compliment string:", e);
}
}
// Fallback: Return what we can find or error messages
console.warn("⚠️ Could not parse feedback from response, using fallback");
return {
roast: data.roast || data.feedback?.roast || "Failed to generate roast - response format not recognized",
compliment: data.compliment || data.feedback?.compliment || "Failed to generate compliment - response format not recognized"
};
} catch (err) {
clearTimeout(timeoutId);
if (err.name === 'AbortError') {
throw new Error('AI feedback request timed out. The AI is taking longer than expected.');
}
console.error("❌ Error fetching AI feedback:", err);
throw err;
}
}
// Fetch League data from AWS Lambda APIs
async function fetchLeagueData(showLoading = true, forceRefresh = false) {
// Check if we have user credentials
if (!userCredentials.gameName || !userCredentials.tagLine || !userCredentials.region) {
console.warn("No user credentials found");
throw new Error("Please enter your account information to load data");
}
// If data is already loaded and not forcing refresh, return immediately
if (!forceRefresh && dataLoadState.isLoaded && leagueData.matches.length > 0) {
console.log("✅ Using cached data - instant load");
return Promise.resolve();
}
// If already loading, return the existing promise
if (dataLoadState.isLoading && dataLoadState.loadPromise) {
console.log("⏳ Data already loading, waiting for existing request...");
return dataLoadState.loadPromise;
}
// Mark as loading and create promise
dataLoadState.isLoading = true;
const loadPromise = (async () => {
try {
if (showLoading) {
$('#dynamicContent').html(`
<div class="flex flex-col items-center justify-center py-12">
<div class="animate-spin rounded-full h-12 w-12 border-b-2 border-sky-500 mb-4"></div>
<p class="text-gray-400">Loading player data from API...</p>
<p class="text-gray-500 text-sm mt-2">This may take 10-30 seconds on first request (cold start)</p>
</div>
`);
}
console.log("🚀 Starting data fetch...");
const startTime = Date.now();
// Fetch player stats (match data, rank, champions, etc.)
// Lambda requires api_key field in request body
const apiKeyToUse = userCredentials.apiKey || HARDCODED_API_KEY;
console.log("📤 Calling getPlayerStats with:", {
apiKey: '***',
gameName: userCredentials.gameName,
tagLine: userCredentials.tagLine,
region: userCredentials.region
});
// Ensure we have all required fields
if (!userCredentials.gameName || !userCredentials.tagLine || !userCredentials.region) {
throw new Error("Missing required fields: game_name, tag_line, or region");
}
const playerStats = await getPlayerStats(
apiKeyToUse,
userCredentials.gameName,
userCredentials.tagLine,
userCredentials.region
);
const statsTime = Date.now() - startTime;
console.log(`⏱️ Player stats fetched in ${statsTime}ms`);
// Fetch quests
let questsData = null;
try {
questsData = await getQuests(
userCredentials.gameName,
userCredentials.tagLine,
userCredentials.region
);
const questsTime = Date.now() - startTime - statsTime;
console.log(`⏱️ Quests fetched in ${questsTime}ms`);
} catch (questErr) {
console.warn("Failed to fetch quests, will generate locally:", questErr);
}
// Map API response to leagueData structure
console.log("🔄 Starting data mapping...");
mapAPIDataToLeagueData(playerStats, questsData);
const totalTime = Date.now() - startTime;
console.log(`✅ All data loaded in ${totalTime}ms`);
console.log("📋 Final leagueData structure after mapping:", {
hasRank: !!leagueData.currentRank,
rank: leagueData.currentRank,
matchesCount: leagueData.matches.length,
championsCount: leagueData.mostPlayedChampions.length,
questsCount: leagueData.quests.length,
pastSeasonsCount: leagueData.pastSeasonRanks.length
});
console.log("📋 Full leagueData object:", JSON.stringify(leagueData, null, 2));
// Ensure data is available even if API structure is different
if (!leagueData.currentRank) {
console.warn("⚠️ No rank data found, setting default");
leagueData.currentRank = { tier: 'Unranked', division: 'IV', lp: 0 };
}
if (leagueData.matches.length === 0) {
console.warn("⚠️ No matches found in API response");
}
// Verify data was actually set
if (leagueData.matches.length === 0 && leagueData.mostPlayedChampions.length === 0 && !leagueData.currentRank) {
console.error("❌ CRITICAL: No data was mapped from API! Check the mapping function.");
}
// Mark data as loaded
dataLoadState.isLoaded = true;
dataLoadState.isLoading = false;
dataLoadState.lastLoadTime = Date.now();
dataLoadState.loadPromise = null;
return Promise.resolve();
} catch (error) {
console.error("❌ Error fetching League data:", error);
console.error("❌ Error details:", error.stack);
// Mark as not loading anymore
dataLoadState.isLoading = false;
dataLoadState.loadPromise = null;
if (showLoading) {
// Format error message - check if it's a 403/API key issue
let errorMsg = error.message;
let errorDetails = '';
if (error.message.includes('403') || error.message.includes('Forbidden') || error.message.includes('Account lookup failed')) {
errorDetails = `
<div class="bg-yellow-900/20 border border-yellow-500/50 rounded-lg p-4 mt-4">
<h4 class="text-yellow-400 font-semibold mb-2">⚠️ 403 Forbidden Error</h4>
<p class="text-yellow-300 text-sm mb-2">The Riot API returned a 403 error. This usually means:</p>
<ul class="text-yellow-300 text-sm list-disc list-inside space-y-1">
<li>The API key may be invalid or expired</li>
<li>The API key may not have the required permissions</li>
<li>The player account may not exist or may be private</li>
<li>The region code might be incorrect</li>
</ul>
<p class="text-yellow-300 text-sm mt-3"><strong>Note:</strong> Riot API keys expire after 24 hours. You may need to generate a new key.</p>
</div>
`;
errorMsg = 'Riot API returned 403 Forbidden. Please check the API key and account information.';
}
$('#dynamicContent').html(`
<div class="bg-red-900/20 border border-red-500 rounded-lg p-6">
<h3 class="text-red-400 font-semibold mb-2">Error Loading Data</h3>
<p class="text-gray-300 mb-4">${errorMsg}</p>
${errorDetails}
<p class="text-gray-400 text-sm mt-4 mb-4">Check browser console (F12) for technical details.</p>
<div class="mt-4 space-x-2">
<button onclick="fetchLeagueData(true, true)" class="px-4 py-2 bg-sky-600 hover:bg-sky-700 text-white rounded">
Retry
</button>
<button onclick="handleLogout()" class="px-4 py-2 bg-slate-600 hover:bg-slate-700 text-white rounded">
Try Different Account
</button>
</div>
</div>
`);
}
// Don't fall back to mock data automatically - let user decide
throw error; // Re-throw so caller can handle it
}
})();
// Store promise for reuse
dataLoadState.loadPromise = loadPromise;
return loadPromise;
}
// Calculate OP Score based on role-specific formulas
function calculateOpScore(player, role, matchData) {
// Normalize role to match formula names
const normalizedRole = (role || '').toLowerCase();
const isJungle = normalizedRole.includes('jungle') || normalizedRole === 'jg';
const isMid = normalizedRole.includes('mid') || normalizedRole.includes('middle') || normalizedRole === 'mid';
const isADC = normalizedRole.includes('adc') || normalizedRole.includes('bot') || normalizedRole === 'adc';
const isSupport = normalizedRole.includes('support') || normalizedRole.includes('sup') || normalizedRole === 'support';
// Extract player stats
const kills = player.kills || player.k || 0;
const deaths = player.deaths || player.d || 0;
const assists = player.assists || player.a || 0;
const kda = deaths > 0 ? (kills + assists) / deaths : (kills + assists);
// Get match duration in minutes (default to 25 if not provided)
const dur = matchData.duration || matchData.gameDuration || matchData.gameLength || 25;
const durMinutes = typeof dur === 'number' ? (dur > 100 ? dur / 60 : dur) : 25; // Convert seconds to minutes if needed
// Calculate team totals
const teamKills = matchData.teamKills || matchData.totalKills || (kills + assists + 10); // Fallback estimate
const teamDmg = matchData.teamDamage || matchData.totalDamageDealtToChampions || 100000; // Fallback estimate
// Extract additional stats
const totalDamageDealtToChampions = player.totalDamageDealtToChampions || player.damageDealt || player.damage || 0;
const totalDamageTaken = player.totalDamageTaken || player.damageTaken || 0;
const visionScore = player.visionScore || player.vision || 0;
const cs = player.cs || player.creepScore || player.totalMinionsKilled || (player.csPerMin ? player.csPerMin * durMinutes : 0);
const goldEarned = player.goldEarned || player.gold || player.goldEarned || 0;
const goldRate = goldEarned / Math.max(durMinutes, 1);
const turretTakedowns = player.turretTakedowns || player.turretKills || 0;
const dragonKills = player.dragonKills || player.dragonKills || 0;
const baronKills = player.baronKills || player.baronKills || 0;
// Calculate damage ratio
const dmgRatio = teamDmg > 0 ? (totalDamageDealtToChampions / teamDmg) : 0;
let opScore = 0;
if (isJungle) {
// Jungle: 0.35 * kda + 0.25 * (((dragonKills || 0) + (baronKills || 0)) / dur) + 0.15 * ((visionScore || 0) / dur) + 0.15 * (goldRate / 500) + 0.1 * ((totalDamageDealtToChampions || 0) / teamDmg)
const objectiveScore = ((dragonKills || 0) + (baronKills || 0)) / Math.max(durMinutes, 1);
const visionScorePerMin = (visionScore || 0) / Math.max(durMinutes, 1);
const goldRateScore = goldRate / 500;
const dmgContribution = (totalDamageDealtToChampions || 0) / Math.max(teamDmg, 1);
opScore = 0.35 * kda +
0.25 * objectiveScore +
0.15 * visionScorePerMin +
0.15 * goldRateScore +
0.1 * dmgContribution;
} else if (isMid) {
// Middle: 0.3 * kda + 0.25 * ((kills + assists) / teamKills) + 0.25 * dmgRatio + 0.1 * (cs / dur) + 0.1 * (goldRate / 500)
const killParticipation = (kills + assists) / Math.max(teamKills, 1);
const csPerMin = cs / Math.max(durMinutes, 1);
const goldRateScore = goldRate / 500;
opScore = 0.3 * kda +
0.25 * killParticipation +
0.25 * dmgRatio +
0.1 * csPerMin +
0.1 * goldRateScore;
} else if (isADC) {
// ADC: 0.4 * ((totalDamageDealtToChampions || 0) / teamDmg) + 0.25 * kda + 0.15 * (cs / dur) + 0.1 * (goldRate / 500) + 0.1 * (1 - deaths / Math.max(1, dur))
const dmgContribution = (totalDamageDealtToChampions || 0) / Math.max(teamDmg, 1);
const csPerMin = cs / Math.max(durMinutes, 1);
const goldRateScore = goldRate / 500;
const survivalRate = 1 - (deaths / Math.max(durMinutes, 1));
opScore = 0.4 * dmgContribution +
0.25 * kda +
0.15 * csPerMin +
0.1 * goldRateScore +
0.1 * survivalRate;
} else if (isSupport) {
// Support: 0.35 * kda + 0.3 * ((visionScore || 0) / dur) + 0.15 * (assists / teamKills) + 0.1 * (((totalDamageTaken || 0) / dur) / Math.max(1, (totalDamageDealtToChampions || 0) / dur)) + 0.1 * (((turretTakedowns || 0) + (dragonKills || 0) + (baronKills || 0)) / 5)
const visionScorePerMin = (visionScore || 0) / Math.max(durMinutes, 1);
const assistParticipation = assists / Math.max(teamKills, 1);
const damageTakenPerMin = (totalDamageTaken || 0) / Math.max(durMinutes, 1);
const damageDealtPerMin = (totalDamageDealtToChampions || 0) / Math.max(durMinutes, 1);
const tankRatio = damageTakenPerMin / Math.max(damageDealtPerMin, 1);
const objectiveScore = ((turretTakedowns || 0) + (dragonKills || 0) + (baronKills || 0)) / 5;
opScore = 0.35 * kda +
0.3 * visionScorePerMin +
0.15 * assistParticipation +
0.1 * tankRatio +
0.1 * objectiveScore;
} else {
// Default/OP (Top): 0.3 * kda + 0.25 * dmgRatio + 0.2 * (goldRate / 500) + 0.15 * ((turretTakedowns || 0) / 5) + 0.1 * (cs / dur)
const goldRateScore = goldRate / 500;
const turretScore = (turretTakedowns || 0) / 5;
const csPerMin = cs / Math.max(durMinutes, 1);
opScore = 0.3 * kda +
0.25 * dmgRatio +
0.2 * goldRateScore +
0.15 * turretScore +