-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhandlers.go
More file actions
2055 lines (1845 loc) · 61.5 KB
/
handlers.go
File metadata and controls
2055 lines (1845 loc) · 61.5 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
// ABOUTME: HTTP handlers for SleeperPy web application
// ABOUTME: Includes route handlers for index, lookup, error rendering, and static pages
package main
import (
"context"
"encoding/json"
"fmt"
"html/template"
"log"
"net/http"
"sort"
"strconv"
"strings"
"time"
)
func visitorLogging(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
ip := r.RemoteAddr
if ipHeader := r.Header.Get("X-Forwarded-For"); ipHeader != "" {
ip = ipHeader
}
if logLevel == "debug" {
log.Printf("[VISITOR] IP: %s Path: %s", ip, r.URL.Path)
}
totalVisitors.Inc()
next(w, r)
}
}
func indexHandler(w http.ResponseWriter, r *http.Request) {
trackPageView(r.URL.Path)
trackUserAgent(r.UserAgent())
savedUsername := ""
if cookie, err := r.Cookie("sleeper_username"); err == nil {
savedUsername = cookie.Value
}
savedUsernames := readSavedUsernames(r)
templates.ExecuteTemplate(w, "index.html", IndexPage{
SavedUsername: savedUsername,
SavedUsernames: savedUsernames,
})
}
func signoutHandler(w http.ResponseWriter, r *http.Request) {
cookie := &http.Cookie{
Name: "sleeper_username",
Value: "",
Path: "/",
MaxAge: -1,
HttpOnly: false,
SameSite: http.SameSiteLaxMode,
}
http.SetCookie(w, cookie)
http.SetCookie(w, &http.Cookie{
Name: "sleeper_usernames",
Value: "",
Path: "/",
MaxAge: -1,
HttpOnly: false,
SameSite: http.SameSiteLaxMode,
})
http.Redirect(w, r, "/", http.StatusSeeOther)
}
func readSavedUsernames(r *http.Request) []string {
cookie, err := r.Cookie("sleeper_usernames")
if err != nil || strings.TrimSpace(cookie.Value) == "" {
return nil
}
raw := strings.Split(cookie.Value, ",")
out := make([]string, 0, len(raw))
seen := make(map[string]bool)
for _, item := range raw {
name := strings.TrimSpace(item)
if name == "" {
continue
}
key := strings.ToLower(name)
if seen[key] {
continue
}
seen[key] = true
out = append(out, name)
}
return out
}
func writeSavedUsernames(w http.ResponseWriter, r *http.Request, username string) {
username = strings.TrimSpace(username)
if username == "" {
return
}
accounts := readSavedUsernames(r)
normalized := strings.ToLower(username)
newList := []string{username}
for _, existing := range accounts {
if strings.ToLower(existing) == normalized {
continue
}
newList = append(newList, existing)
}
if len(newList) > 5 {
newList = newList[:5]
}
http.SetCookie(w, &http.Cookie{
Name: "sleeper_usernames",
Value: strings.Join(newList, ","),
Path: "/",
MaxAge: 30 * 24 * 60 * 60,
HttpOnly: false,
SameSite: http.SameSiteLaxMode,
})
}
func privacyHandler(w http.ResponseWriter, r *http.Request) {
trackPageView(r.URL.Path)
tmpl := template.Must(template.ParseFiles("templates/privacy.html"))
if err := tmpl.Execute(w, nil); err != nil {
http.Error(w, "Error rendering privacy policy", http.StatusInternalServerError)
log.Printf("Error rendering privacy.html: %v", err)
}
}
func termsHandler(w http.ResponseWriter, r *http.Request) {
tmpl := template.Must(template.ParseFiles("templates/terms.html"))
if err := tmpl.Execute(w, nil); err != nil {
http.Error(w, "Error rendering terms of service", http.StatusInternalServerError)
log.Printf("Error rendering terms.html: %v", err)
}
}
func roadmapHandler(w http.ResponseWriter, r *http.Request) {
tmpl := template.Must(template.ParseFiles("templates/roadmap.html"))
if err := tmpl.Execute(w, nil); err != nil {
http.Error(w, "Error rendering planned features page", http.StatusInternalServerError)
log.Printf("Error rendering roadmap.html: %v", err)
}
}
func pricingRedirectHandler(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "/roadmap", http.StatusMovedPermanently)
}
func aboutHandler(w http.ResponseWriter, r *http.Request) {
tmpl := template.Must(template.ParseFiles("templates/about.html"))
if err := tmpl.Execute(w, nil); err != nil {
http.Error(w, "Error rendering about page", http.StatusInternalServerError)
log.Printf("Error rendering about.html: %v", err)
}
}
func faqHandler(w http.ResponseWriter, r *http.Request) {
tmpl := template.Must(template.ParseFiles("templates/faq.html"))
if err := tmpl.Execute(w, nil); err != nil {
http.Error(w, "Error rendering FAQ page", http.StatusInternalServerError)
log.Printf("Error rendering faq.html: %v", err)
}
}
func importHandler(w http.ResponseWriter, r *http.Request) {
trackPageView(r.URL.Path)
provider := strings.ToLower(strings.TrimSpace(r.URL.Query().Get("provider")))
leagueID := strings.TrimSpace(r.URL.Query().Get("league_id"))
seasonRaw := strings.TrimSpace(r.URL.Query().Get("season"))
swid := strings.TrimSpace(r.URL.Query().Get("swid"))
espnS2 := strings.TrimSpace(r.URL.Query().Get("espn_s2"))
if provider == "" || leagueID == "" {
http.Error(w, "provider and league_id are required", http.StatusBadRequest)
return
}
season := 0
if seasonRaw != "" {
n, err := strconv.Atoi(seasonRaw)
if err != nil || n < 2000 || n > 2100 {
http.Error(w, "season must be a valid year", http.StatusBadRequest)
return
}
season = n
}
importer, err := getImporter(provider)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
opts := ImportOptions{
LeagueID: leagueID,
Season: season,
SWID: swid,
ESPN_S2: espnS2,
}
ctx, cancel := context.WithTimeout(r.Context(), 12*time.Second)
defer cancel()
league, err := importer.ImportLeague(ctx, opts)
if err != nil {
http.Error(w, err.Error(), http.StatusBadGateway)
return
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(league)
}
func robotsHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/plain")
fmt.Fprint(w, `User-agent: *
Allow: /
Disallow: /lookup
Disallow: /metrics
Disallow: /signout
Sitemap: https://sleeperpy.com/sitemap.xml
`)
}
func sitemapHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/xml")
fmt.Fprint(w, `<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url>
<loc>https://sleeperpy.com/</loc>
<priority>1.0</priority>
</url>
<url>
<loc>https://sleeperpy.com/about</loc>
<priority>0.8</priority>
</url>
<url>
<loc>https://sleeperpy.com/faq</loc>
<priority>0.7</priority>
</url>
<url>
<loc>https://sleeperpy.com/roadmap</loc>
<priority>0.7</priority>
</url>
<url>
<loc>https://sleeperpy.com/demo</loc>
<priority>0.6</priority>
</url>
<url>
<loc>https://sleeperpy.com/privacy</loc>
<priority>0.3</priority>
</url>
<url>
<loc>https://sleeperpy.com/terms</loc>
<priority>0.3</priority>
</url>
</urlset>
`)
}
func demoHandler(w http.ResponseWriter, r *http.Request) {
trackPageView(r.URL.Path)
demoLeague := LeagueData{
LeagueName: "Example League (Demo)",
Scoring: "PPR",
IsDynasty: false,
HasMatchups: true,
LeagueSize: 12,
RosterSlots: "1 QB, 2 RB, 3 WR, 1 TE, 1 FLEX, 1 K, 1 DEF, 5 BN",
Starters: []PlayerRow{
{Pos: "QB", Name: "Patrick Mahomes", Tier: 1},
{Pos: "RB", Name: "Saquon Barkley", Tier: 2},
{Pos: "RB", Name: "Derrick Henry", Tier: 5, IsTierWorseThanBench: true},
{Pos: "WR", Name: "CeeDee Lamb", Tier: 1},
{Pos: "WR", Name: "Garrett Wilson", Tier: 4},
{Pos: "WR", Name: "Terry McLaurin", Tier: 5},
{Pos: "TE", Name: "Travis Kelce", Tier: 1},
{Pos: "FLEX", Name: "Josh Jacobs", Tier: 6, IsFlex: true},
},
Bench: []PlayerRow{
{Pos: "QB", Name: "Justin Herbert", Tier: 3},
{Pos: "RB", Name: "Aaron Jones", Tier: 4, ShouldSwapIn: true},
{Pos: "WR", Name: "Brandon Aiyuk", Tier: 3},
{Pos: "WR", Name: "Amari Cooper", Tier: 6},
{Pos: "TE", Name: "Sam LaPorta", Tier: 2},
},
TopFreeAgents: []PlayerRow{
{Pos: "RB", Name: "Brian Robinson", Tier: 5, IsFreeAgent: true, IsUpgrade: true, UpgradeFor: "Josh Jacobs", UpgradeType: "Starter"},
{Pos: "WR", Name: "Zay Flowers", Tier: 4, IsFreeAgent: true, IsUpgrade: true, UpgradeFor: "Amari Cooper", UpgradeType: "Bench"},
},
AvgTier: "3.1",
AvgOppTier: "2.5",
WinProb: "38%",
}
page := TiersPage{
Leagues: []LeagueData{demoLeague},
Username: "demo",
}
if err := templates.ExecuteTemplate(w, "tiers.html", page); err != nil {
log.Printf("[ERROR] Demo template error: %v", err)
http.Error(w, "Error rendering demo", http.StatusInternalServerError)
}
}
func lookupHandler(w http.ResponseWriter, r *http.Request) {
totalLookups.Inc()
debugLog("[DEBUG] /lookup handler called")
r.ParseForm()
username := r.FormValue("username")
llmMode := strings.ToLower(strings.TrimSpace(r.FormValue("llm")))
debugLog("[DEBUG] Username submitted: %s", username)
if username == "" {
debugLog("[DEBUG] No username provided")
totalErrors.Inc()
renderError(w, "No username provided. Please enter your Sleeper username on the homepage and try again.")
return
}
// 1. Get user ID
user, err := appProvider.FetchUser(username)
if err != nil || user["user_id"] == nil {
log.Printf("[ERROR] User not found or error: %v", err)
totalErrors.Inc()
renderError(w, fmt.Sprintf("User \"%s\" not found on Sleeper. Double-check your username (it's case-sensitive) — you can find it in the Sleeper app under Settings.", username))
return
}
userID := user["user_id"].(string)
// 2. Get leagues (check current year and previous year for dynasty leagues)
year := time.Now().Year()
leagues, err := appProvider.FetchUserLeagues(userID, year)
if err != nil {
debugLog("[DEBUG] Error fetching leagues for year %d: %v", year, err)
}
// Also fetch previous year leagues (dynasty leagues often stay on previous season)
previousYear := year - 1
previousYearLeagues, err := appProvider.FetchUserLeagues(userID, previousYear)
if err != nil {
debugLog("[DEBUG] Error fetching leagues for year %d: %v", previousYear, err)
} else {
// Append previous year leagues to current year leagues
leagues = append(leagues, previousYearLeagues...)
}
// Sleeper can return the same league when querying adjacent seasons.
// Keep one copy per league_id to avoid duplicate entries in the selector.
leagueByID := make(map[string]map[string]interface{}, len(leagues))
dedupedLeagues := make([]map[string]interface{}, 0, len(leagues))
duplicateCount := 0
for _, league := range leagues {
leagueID, ok := league["league_id"].(string)
if !ok || leagueID == "" {
continue
}
if _, exists := leagueByID[leagueID]; exists {
duplicateCount++
continue
}
leagueByID[leagueID] = league
dedupedLeagues = append(dedupedLeagues, league)
}
if duplicateCount > 0 {
debugLog("[DEBUG] Removed %d duplicate league entries from merged season fetch", duplicateCount)
}
leagues = dedupedLeagues
if len(leagues) == 0 {
log.Printf("[ERROR] No leagues found for user %s", userID)
totalErrors.Inc()
renderError(w, fmt.Sprintf("No leagues found for \"%s\". Make sure you've joined a Sleeper league for the current or previous NFL season. Dynasty leagues from last season are also checked.", username))
return
}
// 3. Get current NFL week from Sleeper API
state, err := appProvider.FetchNFLState()
if err != nil {
log.Printf("[ERROR] Could not get current NFL week: %v", err)
totalErrors.Inc()
renderError(w, "The Sleeper API is temporarily unavailable. Please try again in a few minutes.")
return
}
week := int(state["week"].(float64))
// 4. Get players data (cached for 1 hour)
players, err := fetchPlayers()
if err != nil {
log.Printf("[ERROR] Could not fetch players data: %v", err)
totalErrors.Inc()
renderError(w, "Could not fetch player data from Sleeper. This usually means the Sleeper API is under heavy load — please try again in a few minutes.")
return
}
// 4.5. Fetch dynasty values if any dynasty leagues exist
var dynastyValues map[string]DynastyValue
var dynastyValueDate string
hasDynasty := false
for _, league := range leagues {
if isDynastyLeague(league) {
hasDynasty = true
break
}
}
if hasDynasty {
dynastyValues, dynastyValueDate = fetchDynastyValues()
}
// Check if user has premium access and if premium features are enabled
isPremium := isPremiumUsername(username)
premiumEnabled := hasOpenRouterKey()
// 5. Process each league
var leagueResults []LeagueData
log.Printf("[INFO] Processed %s with %d leagues", username, len(leagues))
totalLeagues.Add(float64(len(leagues)))
// Sort leagues: dynasty leagues first, then by name
sort.Slice(leagues, func(i, j int) bool {
isDynastyI := isDynastyLeague(leagues[i])
isDynastyJ := isDynastyLeague(leagues[j])
if isDynastyI != isDynastyJ {
return isDynastyI // Dynasty leagues come first
}
nameI, _ := leagues[i]["name"].(string)
nameJ, _ := leagues[j]["name"].(string)
return nameI < nameJ
})
for _, league := range leagues {
leagueID := league["league_id"].(string)
leagueName := league["name"].(string)
season := leagueSeasonString(league)
// Check if this is a dynasty league
isDynasty := isDynastyLeague(league)
// Determine scoring type
scoring := "PPR"
if scoringSettings, ok := league["scoring_settings"].(map[string]interface{}); ok {
if rec, ok := scoringSettings["rec"].(float64); ok {
if rec == 0.5 {
scoring = "Half PPR"
} else if rec == 0.0 {
scoring = "Standard"
}
}
}
// Debug: Check league roster_positions
if rosterPositions, ok := league["roster_positions"].([]interface{}); ok {
debugLog("[DEBUG] League roster_positions: %v", rosterPositions)
} else {
debugLog("[DEBUG] roster_positions not found in league settings")
}
// Get rosters and matchups
rosters, err := appProvider.FetchLeagueRosters(leagueID)
if err != nil {
log.Printf("[ERROR] Error fetching rosters for league %s: %v", leagueName, err)
totalErrors.Inc()
continue
}
totalTeams.Add(float64(len(rosters)))
matchups, err := appProvider.FetchLeagueMatchups(leagueID, week)
hasMatchups := (err == nil && len(matchups) > 0)
if !hasMatchups {
if isDynasty {
log.Printf("[INFO] No matchups for league %s week %d (dynasty league in offseason)", leagueName, week)
} else {
log.Printf("[ERROR] No matchups found for league %s week %d: %v", leagueName, week, err)
totalErrors.Inc()
continue
}
}
// Find user roster
var userRoster map[string]interface{}
for _, r := range rosters {
if r["owner_id"] == userID {
userRoster = r
break
}
}
if userRoster == nil {
log.Printf("[ERROR] No user roster found for league %s", leagueName)
totalErrors.Inc()
continue
}
starters := toStringSlice(userRoster["starters"])
allPlayers := toStringSlice(userRoster["players"])
irPlayers := toStringSlice(userRoster["reserve"])
bench := diff(allPlayers, starters)
// Add IR players to bench if not already present
for _, ir := range irPlayers {
found := false
for _, b := range bench {
if b == ir {
found = true
break
}
}
if !found {
bench = append(bench, ir)
}
}
debugLog("[DEBUG] After IR merge, Bench: %v", bench)
// Find opponent (only if we have matchups)
var myMatchup, oppMatchup map[string]interface{}
oppStarters := []string{}
if hasMatchups {
for _, m := range matchups {
if m["roster_id"] == userRoster["roster_id"] {
myMatchup = m
break
}
}
if myMatchup != nil {
for _, m := range matchups {
if m["matchup_id"] == myMatchup["matchup_id"] && m["roster_id"] != userRoster["roster_id"] {
oppMatchup = m
break
}
}
}
debugLog("[DEBUG] MyMatchup: %v | OppMatchup: %v", myMatchup, oppMatchup)
if oppMatchup != nil {
oppStarters = toStringSlice(oppMatchup["starters"])
}
debugLog("[DEBUG] Opponent Starters: %v", oppStarters)
}
// Fetch Boris Chen tiers
borisTiers := fetchBorisTiers(scoring)
debugLog("[DEBUG] Boris Tiers loaded for scoring: %s", scoring)
// Get roster positions from league settings
var leagueRosterPositions []string
if rp, ok := league["roster_positions"].([]interface{}); ok {
for _, pos := range rp {
if posStr, ok := pos.(string); ok {
leagueRosterPositions = append(leagueRosterPositions, posStr)
}
}
}
debugLog("[DEBUG] Parsed roster positions for league: %v", leagueRosterPositions)
// Build rows for roster
var benchUnrankedRows []PlayerRow
benchRows, _, _ := buildRowsWithPositions(bench, players, borisTiers, false, nil, irPlayers, nil)
debugLog("[DEBUG] Built benchRows: %v", benchRows)
bestBenchTier := make(map[string]int)
for _, row := range benchRows {
pos := row.Pos
tier, ok := row.Tier.(int)
if ok && tier > 0 {
if best, exists := bestBenchTier[pos]; !exists || tier < best {
bestBenchTier[pos] = tier
}
}
}
debugLog("[DEBUG] Best bench tier map: %v", bestBenchTier)
// Debug: Log starters with their designated positions
for i, pid := range starters {
if i < len(leagueRosterPositions) {
if p, ok := players[pid].(map[string]interface{}); ok {
name := getPlayerName(p)
debugLog("[DEBUG] Starter %d: %s -> Designated position: %s", i, name, leagueRosterPositions[i])
}
}
}
startersRows, unrankedRows, starterTiers := buildRowsWithPositions(starters, players, borisTiers, true, leagueRosterPositions, irPlayers, bestBenchTier)
debugLog("[DEBUG] Built startersRows: %v", startersRows)
for i, row := range startersRows {
debugLog("[DEBUG] Row %d: Pos=%s, Name=%s, Tier=%v", i, row.Pos, row.Name, row.Tier)
}
// --- FLEX/SUPERFLEX MARKING ---
// Mark FLEX and SUPERFLEX positions based on league roster configuration
// and re-rank them using FLEX tiers (only for FLEX-eligible positions: RB/WR/TE)
for i, row := range startersRows {
if row.Pos == "FLEX" || row.Pos == "SUPER_FLEX" {
pid := starters[i]
if p, ok := players[pid].(map[string]interface{}); ok {
name := getPlayerName(p)
actualPos, _ := p["position"].(string)
isFlexEligible := actualPos == "RB" || actualPos == "WR" || actualPos == "TE"
flxTier := findTier(borisTiers["FLX"], name)
if flxTier > 0 && isFlexEligible {
// Re-rank FLEX-eligible positions (RB/WR/TE) using FLEX tier
if row.Pos == "FLEX" {
startersRows[i].IsFlex = true
debugLog("[DEBUG] FLEX position: %s, re-ranking from tier %v to FLX tier %d", name, row.Tier, flxTier)
} else {
startersRows[i].IsSuperflex = true
debugLog("[DEBUG] SUPERFLEX position: %s, re-ranking from tier %v to FLX tier %d", name, row.Tier, flxTier)
}
startersRows[i].Tier = flxTier
} else {
// For QBs or players without FLEX tier, just mark the slot but keep position tier
if row.Pos == "FLEX" {
startersRows[i].IsFlex = true
debugLog("[DEBUG] FLEX position: %s, keeping position tier %v (pos: %s)", name, row.Tier, actualPos)
} else {
startersRows[i].IsSuperflex = true
debugLog("[DEBUG] SUPERFLEX position: %s, keeping position tier %v (pos: %s)", name, row.Tier, actualPos)
}
}
}
}
}
// Recalculate starterTiers after FLEX re-ranking (whether from API or heuristic)
starterTiers = []int{}
for _, row := range startersRows {
if t, ok := row.Tier.(int); ok && t > 0 {
starterTiers = append(starterTiers, t)
}
}
worstStarterTier := make(map[string]int)
for _, row := range startersRows {
pos := row.Pos
tier, ok := row.Tier.(int)
if ok && tier > 0 {
if worst, exists := worstStarterTier[pos]; !exists || tier > worst {
worstStarterTier[pos] = tier
}
}
}
debugLog("[DEBUG] Worst starter tier map: %v", worstStarterTier)
benchRows, benchUnrankedRows, _ = buildRowsWithPositions(bench, players, borisTiers, false, nil, irPlayers, worstStarterTier)
// Detect if this is a superflex league
isSuperFlex := false
for _, pos := range leagueRosterPositions {
if pos == "SUPER_FLEX" {
isSuperFlex = true
break
}
}
debugLog("[DEBUG] League is superflex: %v", isSuperFlex)
// Enrich rows with dynasty values (if this is a dynasty league)
if isDynasty && dynastyValues != nil {
enrichRowsWithDynastyValues(startersRows, dynastyValues, isSuperFlex)
enrichRowsWithDynastyValues(unrankedRows, dynastyValues, isSuperFlex)
enrichRowsWithDynastyValues(benchRows, dynastyValues, isSuperFlex)
enrichRowsWithDynastyValues(benchUnrankedRows, dynastyValues, isSuperFlex)
debugLog("[DEBUG] Enriched starter and bench rows with dynasty values")
}
// Don't re-rank bench TEs to FLEX tier - keep them at their position-specific tier for display
// Bench RB/WR/TE comparison with FLEX starters happens in free agent logic using FLEX tier lookup,
// but we don't change the display tier here
_, _, oppTiers := buildRowsWithPositions(oppStarters, players, borisTiers, true, nil, nil, nil)
// --- FREE AGENTS LOGIC ---
// Find all rostered player IDs
rostered := map[string]bool{}
for _, r := range rosters {
for _, pid := range toStringSlice(r["players"]) {
rostered[pid] = true
}
for _, pid := range toStringSlice(r["reserve"]) {
rostered[pid] = true
}
}
debugLog("[DEBUG] Rostered player IDs: %v", rostered)
// Find free agents: not rostered, not on user's team, valid tier
type faInfo struct {
pid string
percent float64
tier int
pos string
name string
isUpgrade bool
upgradeFor string
upgradeType string
tierDiff int // How much better this FA is than the player it replaces
}
faList := []faInfo{}
for pid, p := range players {
if _, ok := rostered[pid]; ok {
continue
}
pm, ok := p.(map[string]interface{})
if !ok || pm["active"] == false {
continue
}
pos, _ := pm["position"].(string)
if pos == "" || (pos != "QB" && pos != "RB" && pos != "WR" && pos != "TE" && pos != "K" && pos != "DEF" && pos != "DST") {
continue
}
name := getPlayerName(pm)
lookupPos := pos
if lookupPos == "DEF" {
lookupPos = "DST"
}
// Determine which tier to use and how to compare
// For RB/WR/TE: try FLEX tier first
flexTier := 0
posTier := 0
isFlexEligible := pos == "RB" || pos == "WR" || pos == "TE"
if isFlexEligible {
flexTier = findTier(borisTiers["FLX"], name)
posTier = findTier(borisTiers[lookupPos], name)
} else {
posTier = findTier(borisTiers[lookupPos], name)
}
// Skip if player has no valid tiers at all
if flexTier <= 0 && posTier <= 0 {
continue
}
percent := 0.0
if v, ok := pm["roster_percent"].(float64); ok {
percent = v
} else if v, ok := pm["roster_percent"].(string); ok {
percent, _ = strconv.ParseFloat(v, 64)
}
// Check if this FA is an upgrade for any position on the team
isUpgrade := false
upgradeFor := ""
upgradeType := ""
tierDiff := 0
finalTier := 0
// For RB/WR/TE: use position-specific tier for display and comparison
// (Bench TEs now display their TE tier, not FLEX tier)
if isFlexEligible && posTier > 0 {
finalTier = posTier
for _, row := range startersRows {
// Skip non-flex positions like QB/K/DST
if row.Pos == "QB" || row.Pos == "K" || row.Pos == "DST" {
continue
}
// TEs only compare to TE starters (not FLEX slots)
// RB/WR can compare to same-position starters OR FLEX/SUPERFLEX starters
var canReplace bool
if pos == "TE" {
// TE only compares to TE position
canReplace = (row.Pos == pos)
} else {
// RB/WR can compare to same position OR FLEX slots
canReplace = (row.IsFlex || row.IsSuperflex) || (row.Pos == pos)
}
if !canReplace {
continue
}
t, ok := row.Tier.(int)
if ok && t > 0 && posTier < t {
diff := t - posTier
if diff > tierDiff {
isUpgrade = true
upgradeFor = stripHTML(row.Name)
if row.IsFlex || row.IsSuperflex {
upgradeType = "Starter (FLEX)"
} else {
upgradeType = "Starter"
}
tierDiff = diff
}
}
}
// Also check bench RB/WR/TE (but skip IR players)
if !isUpgrade {
for _, row := range benchRows {
if strings.Contains(row.Name, "(IR)") {
continue
}
if row.Pos != "RB" && row.Pos != "WR" && row.Pos != "TE" {
continue
}
// Only compare if same position (e.g., RB FA vs RB bench, not RB vs TE)
if row.Pos != pos {
continue
}
t, ok := row.Tier.(int)
if ok && t > 0 && posTier < t {
diff := t - posTier
if diff > tierDiff {
isUpgrade = true
upgradeFor = stripHTML(row.Name)
upgradeType = "Bench"
tierDiff = diff
}
}
}
}
} else if posTier > 0 {
// For QB/K/DST or RB/WR/TE without position tier: use position-specific comparison
finalTier = posTier
for _, row := range startersRows {
if row.Pos == pos {
t, ok := row.Tier.(int)
if ok && t > 0 && posTier < t {
diff := t - posTier
if diff > tierDiff {
isUpgrade = true
upgradeFor = stripHTML(row.Name)
upgradeType = "Starter"
tierDiff = diff
}
}
}
}
// Check bench (but skip IR players)
if !isUpgrade {
for _, row := range benchRows {
if strings.Contains(row.Name, "(IR)") {
continue
}
if row.Pos == pos {
t, ok := row.Tier.(int)
if ok && t > 0 && posTier < t {
diff := t - posTier
if diff > tierDiff {
isUpgrade = true
upgradeFor = stripHTML(row.Name)
upgradeType = "Bench"
tierDiff = diff
}
}
}
}
}
} else {
continue // No valid tier to use
}
debugLog("[DEBUG] FA: %s | Pos: %s | PosTier: %d | FlexTier: %d | FinalTier: %d | IsUpgrade: %v | UpgradeFor: %s | UpgradeType: %s | TierDiff: %d", name, pos, posTier, flexTier, finalTier, isUpgrade, upgradeFor, upgradeType, tierDiff)
faList = append(faList, faInfo{pid, percent, finalTier, pos, name, isUpgrade, upgradeFor, upgradeType, tierDiff})
}
debugLog("[DEBUG] Free agent candidates: %d total", len(faList))
// Group by position first
faByPos := map[string][]faInfo{}
for _, fa := range faList {
faByPos[fa.pos] = append(faByPos[fa.pos], fa)
}
// For each position, sort by: upgrades first (by tier diff), then by tier quality, then by roster %
freeAgentsByPos := map[string][]PlayerRow{}
faOrder := []string{"QB", "RB", "WR", "TE", "DST", "K"}
for _, pos := range faOrder {
posList := faByPos[pos]
if len(posList) == 0 {
continue
}
// Sort: upgrades first (by tier diff desc), then by tier asc (better tier), then by roster % desc
sort.Slice(posList, func(i, j int) bool {
// Upgrades before non-upgrades
if posList[i].isUpgrade != posList[j].isUpgrade {
return posList[i].isUpgrade
}
// Among upgrades, sort by tier difference (bigger improvement first)
if posList[i].isUpgrade && posList[j].isUpgrade {
if posList[i].tierDiff != posList[j].tierDiff {
return posList[i].tierDiff > posList[j].tierDiff
}
}
// Then by tier (better tier first)
if posList[i].tier != posList[j].tier {
return posList[i].tier < posList[j].tier
}
// Finally by roster percentage
return posList[i].percent > posList[j].percent
})
// Take top 3, but prioritize upgrades - if we have upgrades, show up to 5
// Exception: only show 2 kickers max
limit := 3
upgradeCount := 0
for _, fa := range posList {
if fa.isUpgrade {
upgradeCount++
}
}
if upgradeCount > 3 {
limit = 5 // Show more if we have many upgrade options
}
if pos == "K" {
limit = 2 // Only show 2 kickers max
}
if len(posList) > limit {
posList = posList[:limit]
}
rows := []PlayerRow{}
for _, fa := range posList {
rows = append(rows, PlayerRow{
Pos: fa.pos,
Name: fa.name,
Tier: fa.tier,
IsFreeAgent: true,
IsUpgrade: fa.isUpgrade,
UpgradeFor: fa.upgradeFor,
UpgradeType: fa.upgradeType,
RosterPercent: fa.percent,
})
}
if len(rows) > 0 {
freeAgentsByPos[pos] = rows
}
}
// Enrich free agents with dynasty values
if isDynasty && dynastyValues != nil {
for pos, faRows := range freeAgentsByPos {
enrichRowsWithDynastyValues(faRows, dynastyValues, isSuperFlex)
freeAgentsByPos[pos] = faRows // Update the map with enriched rows
}
debugLog("[DEBUG] Enriched free agents by position with dynasty values")
}
debugLog("[DEBUG] Final freeAgentsByPos: %v", freeAgentsByPos)
// Create a combined prioritized list of top free agents across all positions
allFAs := []PlayerRow{}
for _, rows := range freeAgentsByPos {
allFAs = append(allFAs, rows...)
}
debugLog("[DEBUG] Combined FA list has %d players", len(allFAs))
// Sort by: upgrades first, then FLEX-eligible positions (RB/WR/TE), then by tier quality
sort.Slice(allFAs, func(i, j int) bool {
// Upgrades before non-upgrades
if allFAs[i].IsUpgrade != allFAs[j].IsUpgrade {
return allFAs[i].IsUpgrade
}
// Among same upgrade status, prioritize FLEX-eligible positions (RB/WR/TE)
isFlex_i := allFAs[i].Pos == "RB" || allFAs[i].Pos == "WR" || allFAs[i].Pos == "TE"
isFlex_j := allFAs[j].Pos == "RB" || allFAs[j].Pos == "WR" || allFAs[j].Pos == "TE"
if isFlex_i != isFlex_j {
return isFlex_i
}
// Then by tier (better tier first)
ti, _ := allFAs[i].Tier.(int)
tj, _ := allFAs[j].Tier.(int)
return ti < tj
})
// Take top 12 most relevant FAs (more to ensure we show FLEX options)
limit := 12
if len(allFAs) < limit {
limit = len(allFAs)
}
var topFreeAgents []PlayerRow
if limit > 0 {
topFreeAgents = allFAs[:limit]
// Enrich top free agents with dynasty values
if isDynasty && dynastyValues != nil {
enrichRowsWithDynastyValues(topFreeAgents, dynastyValues, isSuperFlex)
debugLog("[DEBUG] Enriched top free agents with dynasty values")
}
}
debugLog("[DEBUG] Top free agents: %d selected from %d", len(topFreeAgents), len(allFAs))
// Dynasty mode: generate value-based free agent recommendations and calculate total roster value
var topFreeAgentsByValue []PlayerRow
var totalRosterValue int
if isDynasty && dynastyValues != nil {
// Calculate total roster value (starters + bench)
for _, row := range startersRows {
totalRosterValue += row.DynastyValue
}
for _, row := range benchRows {
totalRosterValue += row.DynastyValue
}
debugLog("[DEBUG] Total roster value: %d", totalRosterValue)
// Find lowest dynasty values on current roster (to identify upgrade targets)
lowestRosterValue := make(map[string]int) // pos -> lowest value on roster
for _, row := range startersRows {
if row.DynastyValue > 0 {
if lowest, exists := lowestRosterValue[row.Pos]; !exists || row.DynastyValue < lowest {
lowestRosterValue[row.Pos] = row.DynastyValue
}
}
}
for _, row := range benchRows {
actualPos := row.Pos
// Skip positions like FLEX, use actual player position for comparison
if actualPos != "FLEX" && actualPos != "SUPER_FLEX" && row.DynastyValue > 0 {
if lowest, exists := lowestRosterValue[actualPos]; !exists || row.DynastyValue < lowest {
lowestRosterValue[actualPos] = row.DynastyValue