{
  "openapi": "3.0.3",
  "info": {
    "title": "NFL Gridiron Intelligence Hub — Live Azure Functions Python API",
    "version": "2.0.0",
    "description": "Live Python v2 Azure Functions REST API querying **Azure SQL Database** (`broadmoorweather.database.windows.net` / `NFL`) across **28 NFL seasons (1999–2026)**, **23 normalized relational tables**, **7,548 games**, **16,666 players**, and **767,293 total rows**.\n\n## Highlights\n1. **Zero-Config Public Read Endpoints (`ANONYMOUS`)**: All read & analytics endpoints support CORS (`*`) and transparent `gzip` compression for payloads > 2 KB.\n2. **Smart Short-TTL Caching + Instant Bypass**: Read endpoints cache responses in worker memory for 30–120 seconds to protect Azure SQL DTUs. Pass `?refresh=1` on any GET endpoint or call `POST /api/refresh` to force a fresh SQL query.\n3. **Automated Weekly Sync**: `nfl_weekly_tuesday_sync` runs every Tuesday at midnight Central Time (`0 0 0 * * 2`), pulling official NFL GSIS/nflverse schedules, rosters, 6-category box scores, and injuries, then recomputing standings and career rollups. On-demand sync is available via `POST /api/sync-nfl` (requires Function Key).",
    "contact": {
      "name": "NFL Gridiron Intelligence Hub",
      "url": "https://nfl.giambattista.io"
    }
  },
  "servers": [
    {
      "url": "https://nfl-giambattista-func.azurewebsites.net",
      "description": "Production — Azure Functions Python v2 API (Direct HTTPS)"
    },
    {
      "url": "https://nfl-container.giambattista.io",
      "description": "Production — Azure Container App (Nginx /api Reverse Proxy)"
    },
    {
      "url": "http://localhost:8080",
      "description": "Local Docker Container (Nginx /api Reverse Proxy)"
    }
  ],
  "tags": [
    {
      "name": "Telemetry & Cache",
      "description": "Database connectivity health checks, 23-table row telemetry, and worker cache invalidation."
    },
    {
      "name": "Dashboard & Season Analytics",
      "description": "Multi-season NFL dashboard bootstrap, fantasy rankings, weekly usage logs, 32-team Defense vs. Position (DvP), team weekly pulse, capology ROI, trades, draft picks, and stadium/surface splits."
    },
    {
      "name": "Encyclopedia & Entity Profiles",
      "description": "Full 16,666-player search directory and dedicated live entity endpoints for individual Game box scores, Player career archives, and Team franchise pages."
    },
    {
      "name": "Admin & Data Sync",
      "description": "On-demand NFL data ingestion from nflverse/nflreadpy into Azure SQL with automatic standings and career rollup recomputation (Function Key protected)."
    }
  ],
  "paths": {
    "/api/health": {
      "get": {
        "tags": ["Telemetry & Cache"],
        "summary": "Live Azure SQL health & 23-table row count telemetry",
        "description": "Verifies live connectivity to Azure SQL (`broadmoorweather.database.windows.net` / `NFL`), returns the active Python SQL driver (`pyodbc` or `pymssql`), loaded season span (`1999–2026`), total game count, and per-table row counts from `sys.partitions`.",
        "operationId": "getHealth",
        "parameters": [
          { "$ref": "#/components/parameters/RefreshParam" }
        ],
        "responses": {
          "200": {
            "description": "Database is reachable and healthy.",
            "content": {
              "application/json": {
                "schema": { "$ref": "#/components/schemas/HealthResponse" },
                "example": {
                  "status": "ok",
                  "mode": "live_azure_sql",
                  "driver": "pymssql",
                  "server": "broadmoorweather.database.windows.net",
                  "database": "NFL",
                  "generated_at": "2026-11-17T19:16:10.412890+00:00",
                  "seasons_range": [1999, 2026],
                  "games_count": 7548,
                  "total_rows": 767293,
                  "table_counts": [
                    { "table_name": "DefensiveStat", "row_count": 286009 },
                    { "table_name": "ReceivingStat", "row_count": 113720 },
                    { "table_name": "Injury", "row_count": 90754 },
                    { "table_name": "RosterEntry", "row_count": 68629 },
                    { "table_name": "RushingStat", "row_count": 59147 },
                    { "table_name": "Contract", "row_count": 48663 },
                    { "table_name": "ReturnStat", "row_count": 28198 },
                    { "table_name": "PassingStat", "row_count": 18026 },
                    { "table_name": "Player", "row_count": 16666 },
                    { "table_name": "KickingStat", "row_count": 14694 },
                    { "table_name": "Game", "row_count": 7548 }
                  ]
                }
              }
            }
          },
          "500": { "$ref": "#/components/responses/ServerError" }
        }
      }
    },
    "/api/refresh": {
      "post": {
        "tags": ["Telemetry & Cache"],
        "summary": "Invalidate short-TTL API cache & verify live SQL state",
        "description": "Clears all cached entries in the Azure Function worker memory and immediately executes a live health check against Azure SQL. Used by the **Live Azure SQL Sync** button in the web app header.",
        "operationId": "postRefreshCache",
        "responses": {
          "200": {
            "description": "Cache cleared and fresh SQL telemetry returned.",
            "content": {
              "application/json": {
                "schema": { "$ref": "#/components/schemas/RefreshResponse" },
                "example": {
                  "status": "ok",
                  "cache_entries_cleared": 6,
                  "generated_at": "2026-11-17T19:20:04.119042+00:00",
                  "games_count": 7548,
                  "total_rows": 767293
                }
              }
            }
          },
          "500": { "$ref": "#/components/responses/ServerError" }
        }
      },
      "get": {
        "tags": ["Telemetry & Cache"],
        "summary": "Invalidate short-TTL API cache (GET convenience alias)",
        "description": "GET convenience alias for `POST /api/refresh` so browsers or CLI health probes can flush the worker cache with a simple GET request.",
        "operationId": "getRefreshCache",
        "responses": {
          "200": {
            "description": "Cache cleared and fresh SQL telemetry returned.",
            "content": {
              "application/json": {
                "schema": { "$ref": "#/components/schemas/RefreshResponse" }
              }
            }
          }
        }
      }
    },
    "/api/dashboard": {
      "get": {
        "tags": ["Dashboard & Season Analytics"],
        "summary": "Full dashboard bootstrap + selected season analytics",
        "description": "Primary initialization endpoint for the NFL Gridiron Intelligence Hub. Returns all 32 teams (`v_TeamDirectory`), 28-season franchise standings (`v_Standings`), all 7,548 games (`dbo.Game`), Capology contract ROI (`dbo.Contract`), NFL trade ledger (`v_TradeLedger`), Rounds 1–3 draft picks with career PPR/sacks, stadium/roof/surface splits, QB indoor/outdoor splits, plus the requested season's fantasy rankings, weekly logs, DvP matrix, team pulse, and injury reports.",
        "operationId": "getDashboard",
        "parameters": [
          { "$ref": "#/components/parameters/SeasonQueryParam" },
          { "$ref": "#/components/parameters/RefreshParam" }
        ],
        "responses": {
          "200": {
            "description": "Complete dashboard bootstrap payload (gzip compressed).",
            "content": {
              "application/json": {
                "schema": { "$ref": "#/components/schemas/DashboardResponse" },
                "example": {
                  "generated_at": "2026-11-17T19:16:15.102938+00:00",
                  "api_mode": "live_azure_sql",
                  "server": "broadmoorweather.database.windows.net",
                  "database": "NFL",
                  "active_season": 2025,
                  "seasons": [2026, 2025, 2024, 2023, 2022, 2021, 2020, 2019, 1999],
                  "table_counts": [{ "table_name": "DefensiveStat", "row_count": 286009 }],
                  "teams": [{
                    "team_id": 29, "abbreviation": "SEA", "city": "Seattle", "team_name": "Seahawks",
                    "conference": "NFC", "division": "West", "home_stadium": "Lumen Field",
                    "stadium_city": "Seattle", "surface": "turf", "roof_type": "open", "founded_year": 1976
                  }],
                  "standings": [{
                    "season_year": 2025, "conference": "NFC", "division": "West", "team_id": 29,
                    "abbreviation": "SEA", "team_name": "Seahawks", "wins": 10, "losses": 7, "ties": 0,
                    "win_pct": 0.588, "points_for": 389, "points_against": 368, "point_diff": 21,
                    "division_rank": 2, "made_playoffs": false, "playoff_seed": null,
                    "playoff_result": null, "head_coach": "Mike Macdonald"
                  }],
                  "games": [{
                    "game_id": 1007286, "season_year": 2025, "week": 1, "game_type": "regular",
                    "kickoff": "2025-09-07T16:05:00", "home_team_id": 29, "home_abbr": "SEA",
                    "home_name": "Seahawks", "home_score": 26, "away_team_id": 10, "away_abbr": "DEN",
                    "away_name": "Broncos", "away_score": 20, "winner_abbr": "SEA", "margin": 6,
                    "stadium_name": "Lumen Field", "stadium_city": "Seattle", "stadium_state": "WA",
                    "surface": "turf", "roof_type": "open", "overtime": false
                  }],
                  "season_fantasy": [{
                    "season_year": 2025, "player_id": 109674, "first_name": "Ja'Marr", "last_name": "Chase",
                    "full_name": "Ja'Marr Chase", "position": "WR", "team": "CIN", "games": 17,
                    "passing_yards": 0, "passing_tds": 0, "interceptions": 0,
                    "rushing_yards": 32, "rushing_tds": 0, "targets": 175, "receptions": 127,
                    "receiving_yards": 1708, "receiving_tds": 17,
                    "fantasy_pts_std": 276.0, "fantasy_pts_half_ppr": 339.5, "fantasy_pts_ppr": 403.0,
                    "ppg_ppr": 23.71, "pos_rank_ppr": 1, "pos_rank_half_ppr": 1, "pos_rank_std": 1
                  }]
                }
              }
            }
          },
          "500": { "$ref": "#/components/responses/ServerError" }
        }
      }
    },
    "/api/season-analytics": {
      "get": {
        "tags": ["Dashboard & Season Analytics"],
        "summary": "Live per-season fantasy rankings, weekly logs, DvP & team pulse",
        "description": "Queries Azure SQL for any single NFL season (`1999–2026`) when the user switches the global Season selector. Returns the top 150 season fantasy scorers (with positional ranks across Standard, Half-PPR, and Full-PPR), game-by-game weekly fantasy logs for the top 90 skill players, 32-team Defense vs. Position (DvP) points/yards allowed, weekly team offensive pulse (points for/against + team passer rating), and up to 2,500 weekly injury designations for that season.",
        "operationId": "getSeasonAnalytics",
        "parameters": [
          {
            "name": "season",
            "in": "query",
            "required": false,
            "description": "NFL season year to analyze (`1999` through `2026`). Defaults to `2025`.",
            "schema": { "type": "integer", "minimum": 1999, "maximum": 2026, "default": 2025 },
            "example": 2024
          },
          { "$ref": "#/components/parameters/RefreshParam" }
        ],
        "responses": {
          "200": {
            "description": "Season analytics slice returned from live SQL.",
            "content": {
              "application/json": {
                "schema": { "$ref": "#/components/schemas/SeasonAnalyticsResponse" },
                "example": {
                  "season": 2024,
                  "generated_at": "2026-11-17T19:16:18.221000+00:00",
                  "season_fantasy": [{
                    "season_year": 2024, "player_id": 107234, "full_name": "CeeDee Lamb",
                    "position": "WR", "team": "DAL", "games": 17, "receptions": 101,
                    "receiving_yards": 1194, "receiving_tds": 6, "fantasy_pts_ppr": 263.4,
                    "ppg_ppr": 15.49, "pos_rank_ppr": 8
                  }],
                  "weekly_fantasy": [{
                    "season_year": 2024, "week": 1, "game_type": "regular", "player_id": 107234,
                    "full_name": "CeeDee Lamb", "position": "WR", "team": "DAL", "opp": "CLE",
                    "venue": "AWAY", "targets": 10, "receptions": 5, "receiving_yards": 61,
                    "receiving_tds": 0, "fantasy_pts_ppr": 13.6
                  }],
                  "dvp": [{
                    "season_year": 2024, "def_team": "BAL", "position": "QB", "games_faced": 17,
                    "pts_allowed_ppr_per_game": 18.42, "pts_allowed_half_per_game": 18.42,
                    "pts_allowed_std_per_game": 18.42, "pass_yds_allowed": 4150,
                    "rush_yds_allowed": 312, "rec_yds_allowed": 0
                  }],
                  "team_weekly_pulse": [{
                    "season_year": 2024, "week": 1, "game_type": "regular", "team": "SEA",
                    "opponent": "DEN", "venue": "HOME", "pf": 26, "pa": 20,
                    "pass_yds": 171, "pass_tds": 1, "ints": 1, "sacks_taken": 2, "team_passer_rating": 84.7
                  }],
                  "injuries": [{
                    "season_year": 2024, "team": "SEA", "player_name": "Kenneth Walker III",
                    "position": "RB", "injury_date": "2024-09-13", "body_part": "Oblique", "status": "Doubtful"
                  }]
                }
              }
            }
          },
          "500": { "$ref": "#/components/responses/ServerError" }
        }
      }
    },
    "/api/players": {
      "get": {
        "tags": ["Encyclopedia & Entity Profiles"],
        "summary": "Complete 16,666-player NFL encyclopedia directory (1999–2026)",
        "description": "Returns a compact columnar matrix (`cols` + `rows`) of all **16,666 NFL players** in `dbo.Player` joined with `dbo.PlayerCareerSummary`, including physical measurables, college, draft year/round/pick/team, chronological franchise list, active season span, and career regular-season passing, rushing, receiving, defensive, kicking, return, and PPR fantasy totals.",
        "operationId": "getPlayersDirectory",
        "parameters": [
          { "$ref": "#/components/parameters/RefreshParam" }
        ],
        "responses": {
          "200": {
            "description": "Compact columnar directory of all 16,666 players.",
            "content": {
              "application/json": {
                "schema": { "$ref": "#/components/schemas/PlayersDirectoryResponse" },
                "example": {
                  "generated_at": "2026-11-17T19:16:22.811000+00:00",
                  "cols": [
                    "id", "name", "pos", "side", "status", "ht", "wt", "dob", "college",
                    "teams", "min_yr", "max_yr", "d_yr", "d_rnd", "d_pick", "d_team",
                    "g", "pass_yds", "pass_td", "pass_int", "rush_yds", "rush_td",
                    "rec", "rec_yds", "rec_td", "tkl", "sacks", "def_int", "fgm", "fga",
                    "ret_yds", "ret_td", "ppr"
                  ],
                  "rows": [
                    [
                      109674, "Ja'Marr Chase", "WR", "offense", "ACT", 72, 201, "2000-03-01", "LSU",
                      "CIN", 2021, 2025, 2021, 1, 5, "CIN",
                      62, 0, 0, 0, 65, 0, 395, 5425, 46, 0, 0.0, 0, 0, 0, 0, 0, 1220.0
                    ]
                  ]
                }
              }
            }
          },
          "500": { "$ref": "#/components/responses/ServerError" }
        }
      }
    },
    "/api/game/{game_id}": {
      "get": {
        "tags": ["Encyclopedia & Entity Profiles"],
        "summary": "Live 6-category NFL game box score, stadium details & H2H series",
        "description": "Queries Azure SQL for a single game (`dbo.Game`) by `game_id` and returns:\n- Full scoreboard, kickoff, overtime, stadium, surface, and roof metadata\n- Both teams' season standings & head coaches (`away_standing`, `home_standing`)\n- Complete per-player box-score stat lines across all **6 official stat tables** (`passing`, `rushing`, `receiving`, `defense`, `kicking`, `returns`)\n- Complete 1999–2026 head-to-head series history (`h2h`) between the two franchises.",
        "operationId": "getGameDetail",
        "parameters": [
          {
            "name": "game_id",
            "in": "path",
            "required": true,
            "description": "Unique integer `game_id` from `dbo.Game` (e.g. `1007286`).",
            "schema": { "type": "integer", "example": 1007286 }
          },
          { "$ref": "#/components/parameters/RefreshParam" }
        ],
        "responses": {
          "200": {
            "description": "Complete game box score and head-to-head series.",
            "content": {
              "application/json": {
                "schema": { "$ref": "#/components/schemas/GameDetailResponse" },
                "example": {
                  "generated_at": "2026-11-17T19:16:28.504000+00:00",
                  "game": {
                    "game_id": 1007286, "season_year": 2025, "week": 16, "game_type": "regular",
                    "kickoff": "2025-12-21T16:25:00", "home_team_id": 29, "home_abbr": "SEA",
                    "home_name": "Seahawks", "home_score": 24, "away_team_id": 20, "away_abbr": "MIN",
                    "away_name": "Vikings", "away_score": 27, "winner_abbr": "MIN", "margin": 3,
                    "stadium_name": "Lumen Field", "stadium_city": "Seattle", "stadium_state": "WA",
                    "surface": "turf", "roof_type": "open", "overtime": false, "attendance": 68740
                  },
                  "away_standing": { "abbreviation": "MIN", "wins": 14, "losses": 3, "ties": 0, "win_pct": 0.824, "division_rank": 2, "head_coach": "Kevin O'Connell" },
                  "home_standing": { "abbreviation": "SEA", "wins": 10, "losses": 7, "ties": 0, "win_pct": 0.588, "division_rank": 2, "head_coach": "Mike Macdonald" },
                  "passing": [[1007286, 104312, "SEA", 43, 31, 314, 3, 2, 2, 96.5, "Geno Smith"]],
                  "rushing": [[1007286, 110245, "SEA", 8, 31, 0, 0, "Kenneth Walker III"]],
                  "receiving": [[1007286, 110988, "SEA", 12, 8, 95, 1, 42, "Jaxon Smith-Njigba"]],
                  "defense": [[1007286, 105112, "SEA", 7, 4, 1.0, 0, 0, 1, 0, "Leonard Williams"]],
                  "kicking": [[1007286, 103901, "SEA", 2, 1, 43, 3, 3, "Jason Myers"]],
                  "returns": [[1007286, 111402, "SEA", 2, 54, 1, 12, 0, "Laviska Shenault Jr."]],
                  "h2h": [{ "game_id": 1007286, "season_year": 2025, "week": 16, "game_type": "regular", "away_abbr": "MIN", "away_score": 27, "home_abbr": "SEA", "home_score": 24, "winner_abbr": "MIN", "stadium_name": "Lumen Field", "overtime": false }]
                }
              }
            }
          },
          "404": { "$ref": "#/components/responses/NotFound" },
          "500": { "$ref": "#/components/responses/ServerError" }
        }
      }
    },
    "/api/player/{player_id}": {
      "get": {
        "tags": ["Encyclopedia & Entity Profiles"],
        "summary": "Live player career profile, year-by-year splits, game log, contracts & injuries",
        "description": "Queries Azure SQL for a single player (`dbo.Player`) by `player_id` and aggregates:\n- Biographical profile, draft pedigree (`dbo.DraftPick`), and career franchise timeline\n- Year-by-year **regular-season** (`seasons`) and **postseason** (`post_seasons`) stat splits across all 6 stat categories + roster entries\n- Week-by-week **game log** (`game_log`) for `season` (defaults to the player's most recent active season)\n- OverTheCap contract history (`contracts`), NFL trade transactions (`trades`), and weekly injury designations (`injuries`).",
        "operationId": "getPlayerDetail",
        "parameters": [
          {
            "name": "player_id",
            "in": "path",
            "required": true,
            "description": "Unique integer `player_id` from `dbo.Player` (e.g. `109674` for Ja'Marr Chase).",
            "schema": { "type": "integer", "example": 109674 }
          },
          {
            "name": "season",
            "in": "query",
            "required": false,
            "description": "Optional season year for the week-by-week `game_log` table. Defaults to the player's latest active NFL season.",
            "schema": { "type": "integer", "minimum": 1999, "maximum": 2026 },
            "example": 2025
          },
          { "$ref": "#/components/parameters/RefreshParam" }
        ],
        "responses": {
          "200": {
            "description": "Complete player career archive and game log.",
            "content": {
              "application/json": {
                "schema": { "$ref": "#/components/schemas/PlayerDetailResponse" },
                "example": {
                  "generated_at": "2026-11-17T19:16:29.110000+00:00",
                  "player": {
                    "id": 109674, "name": "Ja'Marr Chase", "pos": "WR", "side": "offense", "status": "ACT",
                    "ht": 72, "wt": 201, "dob": "2000-03-01", "college": "LSU",
                    "teams": ["CIN"], "min_yr": 2021, "max_yr": 2025,
                    "d_yr": 2021, "d_rnd": 1, "d_pick": 5, "d_team": "CIN",
                    "g": 62, "pass_yds": 0, "pass_td": 0, "pass_int": 0, "rush_yds": 65, "rush_td": 0,
                    "rec": 395, "rec_yds": 5425, "rec_td": 46, "tkl": 0, "sacks": 0.0, "def_int": 0,
                    "fgm": 0, "fga": 0, "ret_yds": 0, "ret_td": 0, "ppr": 1220.0
                  },
                  "season_cols": ["yr", "team", "jersey", "g", "att", "cmp", "pass_yds", "pass_td", "pass_int", "sck_taken", "rtg", "car", "rush_yds", "rush_td", "fum", "tgt", "rec", "rec_yds", "rec_td", "yac", "tkl", "ast", "sacks", "def_int", "ff", "pd", "def_td", "fga", "fgm", "fgl", "xpa", "xpm", "kr", "kr_yds", "pr", "pr_yds", "ret_td", "ppr"],
                  "seasons": [[2025, "CIN", 1, 17, 0, 0, 0, 0, 0, 0, null, 3, 32, 0, 0, 175, 127, 1708, 17, 787, 0, 0, 0.0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 403.0]],
                  "post_seasons": [],
                  "active_years": [2025, 2024, 2023, 2022, 2021],
                  "log_season": 2025,
                  "game_log": [{
                    "game_id": 1007201, "season_year": 2025, "week": 1, "game_type": "regular",
                    "kickoff": "2025-09-07T13:00:00", "home_abbr": "CIN", "away_abbr": "NE",
                    "home_score": 10, "away_score": 16, "winner_abbr": "NE", "team": "CIN",
                    "att": 0, "cmp": 0, "pyd": 0, "ptd": 0, "pint": 0, "car": 0, "ryd": 0, "rtd": 0,
                    "tgt": 6, "rec": 6, "recyd": 62, "rectd": 0, "tkl": 0, "sck": 0.0, "dint": 0, "pd": 0,
                    "fgm": 0, "fga": 0, "xpm": 0, "retYds": 0, "retTd": 0
                  }],
                  "contracts": [["CIN", "2021-06-02", "2025-12-31", 30.82, 30.82]],
                  "injuries": [["2023-12-22", "CIN", "Shoulder", "Out"]],
                  "trades": []
                }
              }
            }
          },
          "404": { "$ref": "#/components/responses/NotFound" },
          "500": { "$ref": "#/components/responses/ServerError" }
        }
      }
    },
    "/api/team/{abbr}": {
      "get": {
        "tags": ["Encyclopedia & Entity Profiles"],
        "summary": "Live NFL franchise encyclopedia, season schedule, roster & era leaders",
        "description": "Queries Azure SQL for an NFL franchise by its standard abbreviation (`SEA`, `KC`, `SF`, `BUF`, etc.) and returns:\n- Franchise directory metadata (conference, division, home stadium, surface, roof, founded year)\n- All 1999–2026 year-by-year season records, playoff results & head coaches (`standings`)\n- Full game schedule & scores for `season` (`schedule`)\n- Full deduplicated `season` team roster enriched with each player's height, weight, college, and `season` stat totals (`roster`)\n- All-time modern era (`1999–2026`) top-12 regular-season franchise leaders in Passing, Rushing, Receiving, and Defense (`leaders`)\n- Coaching tenures (`coaches`) and all franchise draft picks (`draft_picks`).",
        "operationId": "getTeamDetail",
        "parameters": [
          {
            "name": "abbr",
            "in": "path",
            "required": true,
            "description": "2- or 3-letter NFL team abbreviation (e.g. `SEA`, `KC`, `SF`, `DAL`, `BUF`, `DET`, `PHI`, `GB`).",
            "schema": { "type": "string", "example": "SEA" }
          },
          {
            "name": "season",
            "in": "query",
            "required": false,
            "description": "Season year (`1999–2026`) for the franchise `schedule` and `roster` tables. Defaults to `2025`.",
            "schema": { "type": "integer", "minimum": 1999, "maximum": 2026, "default": 2025 },
            "example": 2025
          },
          { "$ref": "#/components/parameters/RefreshParam" }
        ],
        "responses": {
          "200": {
            "description": "Complete franchise encyclopedia payload.",
            "content": {
              "application/json": {
                "schema": { "$ref": "#/components/schemas/TeamDetailResponse" },
                "example": {
                  "generated_at": "2026-11-17T19:16:25.304000+00:00",
                  "team": {
                    "team_id": 29, "abbreviation": "SEA", "city": "Seattle", "team_name": "Seahawks",
                    "conference": "NFC", "division": "West", "home_stadium": "Lumen Field",
                    "stadium_city": "Seattle", "surface": "turf", "roof_type": "open", "founded_year": 1976
                  },
                  "view_season": 2025,
                  "seasons": [2026, 2025, 2024, 2023, 1999],
                  "standings": [{
                    "season_year": 2025, "conference": "NFC", "division": "West", "team_id": 29,
                    "abbreviation": "SEA", "team_name": "Seahawks", "wins": 10, "losses": 7, "ties": 0,
                    "win_pct": 0.588, "points_for": 389, "points_against": 368, "point_diff": 21,
                    "division_rank": 2, "made_playoffs": false, "head_coach": "Mike Macdonald"
                  }],
                  "schedule": [{
                    "game_id": 1007286, "season_year": 2025, "week": 1, "game_type": "regular",
                    "kickoff": "2025-09-07T16:05:00", "home_abbr": "SEA", "home_score": 26,
                    "away_abbr": "DEN", "away_score": 20, "winner_abbr": "SEA", "stadium_name": "Lumen Field", "overtime": false
                  }],
                  "roster": [{
                    "player_id": 110988, "name": "Jaxon Smith-Njigba", "pos": "WR", "jersey": 11,
                    "status": "ACT", "ht": 72, "wt": 197, "college": "Ohio State",
                    "pyd": 0, "ptd": 0, "ryd": 26, "rtd": 0, "rec": 100, "recyd": 1130, "rectd": 6,
                    "tkl": 0, "sck": 0.0, "dint": 0, "fgm": 0, "fga": 0
                  }],
                  "leaders": {
                    "passing": [[101845, "Russell Wilson", 158, 3079, 4735, 37059, 292, 87]],
                    "rushing": [[100912, "Shaun Alexander", 119, 2176, 9429, 100]],
                    "receiving": [[102401, "Tyler Lockett", 161, 661, 914, 8594, 61]],
                    "defense": [[101902, "Bobby Wagner", 168, 1566, 27.5, 13, 6, 4]]
                  },
                  "coaches": [["Mike Macdonald", "Head Coach", "2024-01-31", null]],
                  "draft_picks": [[6980, 2023, 1, 20, "SEA", "SEA", 110988, "Jaxon Smith-Njigba", "WR", "Ohio State"]]
                }
              }
            }
          },
          "404": { "$ref": "#/components/responses/NotFound" },
          "500": { "$ref": "#/components/responses/ServerError" }
        }
      }
    },
    "/api/sync-nfl": {
      "post": {
        "tags": ["Admin & Data Sync"],
        "summary": "On-demand NFL season/week data sync into Azure SQL (Function Key)",
        "description": "Pulls the latest official NFL schedules, rosters, 6-category weekly player stats, and weekly injury designations from `nflreadpy` (`nflverse`), upserts them into Azure SQL (`dbo.*`), executes `EXEC dbo.usp_RecomputeStandings` and `EXEC dbo.usp_RefreshCareerSummary`, and clears the live API cache.\n\n**Authentication:** Protected with `AuthLevel.FUNCTION`. Supply your Azure Function Key via the `x-functions-key` header (click **Authorize** in Swagger UI) or `?code=<function_key>` query parameter.",
        "operationId": "postSyncNfl",
        "security": [
          { "FunctionKeyHeader": [] },
          { "FunctionKeyQuery": [] }
        ],
        "parameters": [
          {
            "name": "season",
            "in": "query",
            "required": false,
            "description": "Target NFL season year to sync (defaults to current NFL season).",
            "schema": { "type": "integer", "minimum": 1999, "maximum": 2026 },
            "example": 2026
          },
          {
            "name": "week",
            "in": "query",
            "required": false,
            "description": "Optional specific week (`1–22`) to refresh; omit to sync all weeks of `season`.",
            "schema": { "type": "integer", "minimum": 1, "maximum": 22 },
            "example": 10
          }
        ],
        "requestBody": {
          "required": false,
          "description": "Optional JSON body specifying `season` and/or `week` (overrides or supplements query parameters).",
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "properties": {
                  "season": { "type": "integer", "example": 2026, "description": "NFL season year to synchronize." },
                  "week": { "type": "integer", "example": 10, "description": "Optional NFL week number (`1–22`)." }
                }
              },
              "example": { "season": 2026, "week": 10 }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Database sync committed, standings & career rollups recomputed, and cache invalidated.",
            "content": {
              "application/json": {
                "schema": { "$ref": "#/components/schemas/SyncSummaryResponse" },
                "example": {
                  "status": "success",
                  "timestamp_utc": "2026-11-17T06:00:19.442100+00:00",
                  "season": 2026,
                  "target_week": 10,
                  "new_players_inserted": 4,
                  "roster_entries_refreshed": 1696,
                  "new_games_inserted": 0,
                  "existing_games_updated": 14,
                  "stats_upserted": {
                    "PassingStat": 31,
                    "RushingStat": 104,
                    "ReceivingStat": 218,
                    "DefensiveStat": 482,
                    "KickingStat": 28,
                    "ReturnStat": 41,
                    "Injury": 390
                  },
                  "standings_recomputed": true
                }
              }
            }
          },
          "401": {
            "description": "Missing or invalid Azure Function Key (`x-functions-key` header or `code` query param)."
          },
          "500": { "$ref": "#/components/responses/ServerError" }
        }
      }
    },
    "/fantasy-advisor": {
      "post": {
        "tags": ["Analytics"],
        "operationId": "evaluateFantasyAdvisor",
        "summary": "Stateless multi-week fantasy trajectory & upcoming-week statistical recommendation engine",
        "description": "Evaluates a 7-to-10-slot lineup (`QB, RB1, RB2, WR1, WR2, TE, FLEX, FLEX2, K, DEF`) across played weeks, 3-season trajectory (`Y-2..Y`), 12-team league starter median, and upcoming target-week matchup projections using current & prior NFL statistics (`blend`, `current`, or `prior` model).",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "properties": {
                  "season": { "type": "integer", "example": 2026 },
                  "target_week": { "type": "integer", "example": 10 },
                  "scoring": { "type": "string", "enum": ["ppr", "half", "std"], "default": "ppr" },
                  "model": { "type": "string", "enum": ["blend", "current", "prior"], "default": "blend" },
                  "slots": { "type": "object" }
                }
              }
            }
          }
        },
        "responses": {
          "200": { "description": "Multi-week trajectory, 4-week forecast, starter outlook, and ranked upcoming-week recommendations." },
          "500": { "$ref": "#/components/responses/ServerError" }
        }
      }
    }
  },
  "components": {
    "securitySchemes": {
      "FunctionKeyHeader": {
        "type": "apiKey",
        "in": "header",
        "name": "x-functions-key",
        "description": "Azure Functions host or function key for `nfl-giambattista-func` (required only for `/api/sync-nfl`)."
      },
      "FunctionKeyQuery": {
        "type": "apiKey",
        "in": "query",
        "name": "code",
        "description": "Azure Functions key passed as `?code=...` query string parameter."
      }
    },
    "parameters": {
      "SeasonQueryParam": {
        "name": "season",
        "in": "query",
        "required": false,
        "description": "NFL season year (`1999–2026`) for initial season-scoped analytics. Defaults to the latest season with completed games (`2025`).",
        "schema": { "type": "integer", "minimum": 1999, "maximum": 2026, "default": 2025 },
        "example": 2025
      },
      "RefreshParam": {
        "name": "refresh",
        "in": "query",
        "required": false,
        "description": "Set to `1` (`true`) to bypass the short-TTL worker memory cache and force a fresh live query against Azure SQL.",
        "schema": { "type": "integer", "enum": [0, 1], "default": 0 },
        "example": 0
      }
    },
    "responses": {
      "NotFound": {
        "description": "Requested NFL entity ID or franchise abbreviation was not found in Azure SQL.",
        "content": {
          "application/json": {
            "schema": {
              "type": "object",
              "properties": {
                "status": { "type": "string", "example": "not_found" }
              }
            }
          }
        }
      },
      "ServerError": {
        "description": "Unhandled server or SQL error.",
        "content": {
          "application/json": {
            "schema": {
              "type": "object",
              "properties": {
                "status": { "type": "string", "example": "error" },
                "error": { "type": "string", "example": "SQL connection timeout" }
              }
            }
          }
        }
      }
    },
    "schemas": {
      "TableCount": {
        "type": "object",
        "properties": {
          "table_name": { "type": "string", "example": "DefensiveStat" },
          "row_count": { "type": "integer", "example": 286009 }
        }
      },
      "HealthResponse": {
        "type": "object",
        "properties": {
          "status": { "type": "string", "example": "ok" },
          "mode": { "type": "string", "example": "live_azure_sql" },
          "driver": { "type": "string", "enum": ["pyodbc", "pymssql"] },
          "server": { "type": "string" },
          "database": { "type": "string" },
          "generated_at": { "type": "string", "format": "date-time" },
          "seasons_range": { "type": "array", "items": { "type": "integer" } },
          "games_count": { "type": "integer" },
          "total_rows": { "type": "integer" },
          "table_counts": { "type": "array", "items": { "$ref": "#/components/schemas/TableCount" } }
        }
      },
      "RefreshResponse": {
        "type": "object",
        "properties": {
          "status": { "type": "string", "example": "ok" },
          "cache_entries_cleared": { "type": "integer", "example": 6 },
          "generated_at": { "type": "string", "format": "date-time" },
          "games_count": { "type": "integer", "example": 7548 },
          "total_rows": { "type": "integer", "example": 767293 }
        }
      },
      "DashboardResponse": {
        "type": "object",
        "properties": {
          "generated_at": { "type": "string", "format": "date-time" },
          "api_mode": { "type": "string", "example": "live_azure_sql" },
          "server": { "type": "string" },
          "database": { "type": "string" },
          "active_season": { "type": "integer", "example": 2025 },
          "seasons": { "type": "array", "items": { "type": "integer" } },
          "table_counts": { "type": "array", "items": { "$ref": "#/components/schemas/TableCount" } },
          "teams": { "type": "array", "items": { "type": "object" } },
          "standings": { "type": "array", "items": { "type": "object" } },
          "games": { "type": "array", "items": { "type": "object" } },
          "season_fantasy": { "type": "array", "items": { "type": "object" } },
          "weekly_fantasy": { "type": "array", "items": { "type": "object" } },
          "dvp": { "type": "array", "items": { "type": "object" } },
          "team_weekly_pulse": { "type": "array", "items": { "type": "object" } },
          "injuries": { "type": "array", "items": { "type": "object" } },
          "contracts_roi": { "type": "array", "items": { "type": "object" } },
          "trades": { "type": "array", "items": { "type": "object" } },
          "draft_picks": { "type": "array", "items": { "type": "object" } },
          "env_splits": { "type": "array", "items": { "type": "object" } },
          "stadium_stats": { "type": "array", "items": { "type": "object" } },
          "qb_env_splits": { "type": "array", "items": { "type": "object" } }
        }
      },
      "SeasonAnalyticsResponse": {
        "type": "object",
        "properties": {
          "season": { "type": "integer", "example": 2024 },
          "generated_at": { "type": "string", "format": "date-time" },
          "season_fantasy": { "type": "array", "items": { "type": "object" } },
          "weekly_fantasy": { "type": "array", "items": { "type": "object" } },
          "dvp": { "type": "array", "items": { "type": "object" } },
          "team_weekly_pulse": { "type": "array", "items": { "type": "object" } },
          "injuries": { "type": "array", "items": { "type": "object" } }
        }
      },
      "PlayersDirectoryResponse": {
        "type": "object",
        "properties": {
          "generated_at": { "type": "string", "format": "date-time" },
          "cols": { "type": "array", "items": { "type": "string" } },
          "rows": { "type": "array", "items": { "type": "array", "items": {} } }
        }
      },
      "GameDetailResponse": {
        "type": "object",
        "properties": {
          "generated_at": { "type": "string", "format": "date-time" },
          "game": { "type": "object" },
          "away_standing": { "type": "object" },
          "home_standing": { "type": "object" },
          "passing": { "type": "array", "items": { "type": "array", "items": {} } },
          "rushing": { "type": "array", "items": { "type": "array", "items": {} } },
          "receiving": { "type": "array", "items": { "type": "array", "items": {} } },
          "defense": { "type": "array", "items": { "type": "array", "items": {} } },
          "kicking": { "type": "array", "items": { "type": "array", "items": {} } },
          "returns": { "type": "array", "items": { "type": "array", "items": {} } },
          "h2h": { "type": "array", "items": { "type": "object" } }
        }
      },
      "PlayerDetailResponse": {
        "type": "object",
        "properties": {
          "generated_at": { "type": "string", "format": "date-time" },
          "player": { "type": "object" },
          "season_cols": { "type": "array", "items": { "type": "string" } },
          "seasons": { "type": "array", "items": { "type": "array", "items": {} } },
          "post_seasons": { "type": "array", "items": { "type": "array", "items": {} } },
          "active_years": { "type": "array", "items": { "type": "integer" } },
          "log_season": { "type": "integer" },
          "game_log": { "type": "array", "items": { "type": "object" } },
          "contracts": { "type": "array", "items": { "type": "array", "items": {} } },
          "injuries": { "type": "array", "items": { "type": "array", "items": {} } },
          "trades": { "type": "array", "items": { "type": "array", "items": {} } }
        }
      },
      "TeamDetailResponse": {
        "type": "object",
        "properties": {
          "generated_at": { "type": "string", "format": "date-time" },
          "team": { "type": "object" },
          "view_season": { "type": "integer" },
          "seasons": { "type": "array", "items": { "type": "integer" } },
          "standings": { "type": "array", "items": { "type": "object" } },
          "schedule": { "type": "array", "items": { "type": "object" } },
          "roster": { "type": "array", "items": { "type": "object" } },
          "leaders": { "type": "object" },
          "coaches": { "type": "array", "items": { "type": "array", "items": {} } },
          "draft_picks": { "type": "array", "items": { "type": "array", "items": {} } }
        }
      },
      "SyncSummaryResponse": {
        "type": "object",
        "properties": {
          "status": { "type": "string", "example": "success" },
          "timestamp_utc": { "type": "string", "format": "date-time" },
          "season": { "type": "integer" },
          "target_week": {},
          "new_players_inserted": { "type": "integer" },
          "roster_entries_refreshed": { "type": "integer" },
          "new_games_inserted": { "type": "integer" },
          "existing_games_updated": { "type": "integer" },
          "stats_upserted": { "type": "object" },
          "standings_recomputed": { "type": "boolean" }
        }
      }
    }
  }
}

