#!/usr/bin/env python3
"""Monitor Austria vs Jordan match, save result"""
import json, time, os, sys, subprocess

RESULT_FILE = "/root/match_austria.json"
last_score = "0-0"

for _ in range(20):
    try:
        raw = subprocess.run(
            ["curl", "-sL", "https://site.api.espn.com/apis/site/v2/sports/soccer/fifa.world/scoreboard?dates=20260617"],
            capture_output=True, text=True, timeout=15
        )
        data = json.loads(raw.stdout)
        
        for e in data.get("events", []):
            if "Jordan" not in e.get("name", "") and "Austria" not in e.get("name", ""):
                continue
            
            comp = e["competitions"][0]
            status = comp["status"]["type"]
            state = status.get("state", "")
            detail = status.get("description", "")
            
            teams = {}
            for team in comp.get("competitors", []):
                teams[team["team"]["displayName"]] = team.get("score", "0")
            
            score = f'{teams.get("Austria", "0")}-{teams.get("Jordan", "0")}'
            
            result = {
                "state": state, "detail": detail,
                "score": score,
                "austria": teams.get("Austria", "0"),
                "jordan": teams.get("Jordan", "0"),
                "updated": time.strftime("%Y-%m-%d %H:%M:%S")
            }
            
            with open(RESULT_FILE, "w") as f:
                json.dump(result, f, indent=2)
            
            now = time.strftime("%H:%M:%S")
            if state == "post" or "Full Time" in detail or "Final" in detail:
                print(f"[{now}] MATCH OVER: {score}")
                print(json.dumps(result))
                sys.exit(0)
            else:
                print(f"[{now}] {score} - {detail}", flush=True)
    except Exception as ex:
        print(f"[ERR] {ex}", file=sys.stderr)
    
    time.sleep(90)
