#!/usr/bin/env python3
import requests
import json
import os

API_KEY = os.environ.get("BALLDONTLIE_API_KEY")
if not API_KEY:
    raise RuntimeError("BALLDONTLIE_API_KEY is not set. Put it in the environment (recommended: .env / systemd EnvironmentFile).")
HEADERS = {"Authorization": API_KEY}
BASE_URL = "https://api.balldontlie.io/nfl/v1"

def get_standings(season):
    try:
        url = f"{BASE_URL}/standings?season={season}"
        resp = requests.get(url, headers=HEADERS, timeout=10)
        if resp.status_code == 200:
            return resp.json().get("data", [])
        return []
    except Exception as e:
        print(f"Error fetching standings: {e}")
        return []

def main():
    season = int(os.environ.get("NFL_SEASON", str(__import__("datetime").datetime.utcnow().year)))
    print(f"Fetching NFL {season} Context...")
    context_lines = []
    
    # 1. Standings
    # Try 2025 first (User requested 2025-26)
    standings = get_standings(season)
    header = f"NFL {season} STANDINGS (Live Data):"
    
    if not standings:
        print("2025 Standings empty, trying 2024 fallback...")
        standings = get_standings(2024)
        if standings:
            header = "NFL 2024-2025 STANDINGS (Context Fallback):"
    
    if standings:
        context_lines.append(header)
        
        # Sort by wins
        def get_wins(team):
            return team.get("wins", 0)
        
        standings.sort(key=get_wins, reverse=True)

        for t in standings:
            try:
                name = t.get("team", {}).get("full_name", "Unknown")
                conf = t.get("team", {}).get("conference", "")
                div = t.get("team", {}).get("division", "")
                
                # Correct fields from API inspection
                rec = t.get("overall_record", "N/A")
                wins = t.get("wins", 0)
                losses = t.get("losses", 0)
                
                context_lines.append(f"- {name} ({conf} {div}): {rec}")
            except:
                pass
    else:
        context_lines.append("No Standings Data Available via API.")

    output = "\n".join(context_lines)
    print(f"Generated {len(context_lines)} lines of context.")
    
    output_path = "/var/www/html/eventheodds/airagagent/nfl_context_2025.txt"
    try:
        with open(output_path, "w") as f:
            f.write(output)
        print(f"Saved context to {output_path}")
    except Exception as e:
        print(f"Failed to save to {output_path}: {e}")

if __name__ == "__main__":
    main()
