from utils import Logger
import requests
from jobs.competition import Sportcompetition
from App.models import Matches

class HandleResult():
    def __init__(self):
        self.start()
        
    def start(self):
        for competition in Sportcompetition.competitions:
            try:
                self.get_result(competition)
            except:Logger.error("Something went wrong!")
    
    def get_result(self, competition):
        url = f"https://api.the-odds-api.com/v4/sports/{competition["competition"]}/scores?api_key={competition["api_key"]}&daysFrom=3&dateFormat=iso"
        try:
            print(f"Fetching {competition["name"]} results...")
            res = requests.get(url, timeout=15)
            data = res.json()
            for match in data:
                if not match["completed"]:
                    continue
                if Matches.objects.filter(match_id=match["id"]).exists():
                    self.update_result(match["id"], match["scores"])
                else:
                    self.create_match(match)
        except Exception as e:
            print(e)
            Logger.error("Something went wrong!")
    
    def update_result(self, match_id, scores):
        match = Matches.objects.get(match_id=match_id)
        match.score_home = scores[0]["score"]
        match.score_away = scores[1]["score"]
        match.is_completed = True
        match.save()
        Logger.success(f"Match {match_id} updated successfully.")
    
    def create_match(self, match):
        new_match = Matches.objects.create(
            match_id = match["id"],
            home_team = match["home_team"],
            away_team = match["away_team"],
            is_completed = match["completed"],
            score_home = match["scores"][0]["score"],
            score_away = match["scores"][1]["score"],
            commencement_time = match["commence_time"],
            competition = match["sport_key"],
            isleague = True if not match["sport_key"] in Sportcompetition.cups else False,
            # season =
        )
        new_match.save()
        Logger.success(f"Match {match["id"]} created successfully.")
