#!/usr/bin/env python3
"""Monitor France vs Senegal World Cup match, save result when finished"""
import json, time, os, sys, subprocess

RESULT_FILE = "/root/match_result.json"
EVENT_FILE = "/root/match_events.json"
MATCH_NAME = "Senegal at France"

events = []
if os.path.exists(EVENT_FILE):
    with open(EVENT_FILE) as f:
        events = json.load(f)

last_score = "0-0"

while True:
    try:
        raw = subprocess.run(
            ["curl", "-sL", "https://site.api.espn.com/apis/site/v2/sports/soccer/fifa.world/scoreboard"],
            capture_output=True, text=True, timeout=15
        )
        data = json.loads(raw.stdout)
        
        for e in data.get("events", []):
            if MATCH_NAME not in e.get("name", ""):
                continue
            
            comp = e["competitions"][0]
            status = comp["status"]["type"]
            state = status.get("state", "")
            detail = status.get("description", "")
            
            competitors = {}
            for team in comp.get("competitors", []):
                competitors[team["team"]["displayName"]] = team.get("score", "0")
            
            score = f'{competitors.get("Senegal", "0")}-{competitors.get("France", "0")}'
            
            # Track score changes (goals)
            if score != last_score and last_score != "0-0":
                now = time.strftime("%H:%M:%S")
                events.append({"time": now, "score": score, "detail": detail})
                with open(EVENT_FILE, "w") as f:
                    json.dump(events, f, indent=2)
                print(f"[GOAL] {now} - New score: {score}")
                sys.stdout.flush()
            
            last_score = score
            
            result = {
                "state": state,
                "detail": detail,
                "score": score,
                "senegal": competitors.get("Senegal", "0"),
                "france": competitors.get("France", "0"),
                "events": events,
                "updated": time.strftime("%Y-%m-%d %H:%M:%S")
            }
            
            with open(RESULT_FILE, "w") as f:
                json.dump(result, f, indent=2)
            
            print(f"[{time.strftime('%H:%M')}] {score} - {detail}")
            sys.stdout.flush()
            
            # Match finished
            if state == "post" or "Final" in detail:
                print("== MATCH FINISHED ==")
                print(json.dumps(result))
                sys.stdout.flush()
                sys.exit(0)
                
    except Exception as ex:
        print(f"[ERR] {ex}", file=sys.stderr)
        sys.stderr.flush()
    
    time.sleep(180)  # 3 min intervals
