#!/usr/bin/env python3 """Verify one fixed historical LaLiga row using Python's standard library. No network access, downloads, dependencies or file writes. The report is JSON on stdout; exit status is 0 only when every check passes, otherwise 1. """ import argparse from collections import Counter import csv import hashlib import io import json from pathlib import Path import sys BASE = Path(__file__).resolve().parent COMMIT = "e6744429ee395bc86f247348c6184bb08d4eb361" SOURCE_URL = ( "https://raw.githubusercontent.com/openfootball/football.json/" + COMMIT + "/2019-20/es.1.json" ) SOURCE_SHA256 = "8ade2e46a80a646159af590cb6bcca6a3739a6eebc168a4902aabeb0d1ce6c0d" CSV_URL = "https://futbolconia365.com/estudios/ventaja-local/datos.csv" CSV_SHA256 = "573e43d99a46556303632e788c5d15f44582d40898050487eef989fe01368ce6" CSV_COLUMNS = ["season", "league", "matches", "home_wins", "draws", "away_wins"] COUNT_KEYS = ["matches", "home_wins", "draws", "away_wins"] REQUIRED_MATCH_KEYS = {"round", "date", "team1", "team2", "score"} def verify(source_path, csv_path): report = { "protocol_version": 1, "status": "FAIL", "scope": "LaLiga 2019-20 full-time outcome counts; one published CSV row only", "provenance": { "source_url": SOURCE_URL, "source_commit": COMMIT, "source_license": "CC0-1.0", "source_license_url": "https://creativecommons.org/publicdomain/zero/1.0/", "published_csv_url": CSV_URL, }, "files": {}, "checks": {}, "errors": [], } def check(name, passed, detail=""): report["checks"][name] = bool(passed) if not passed: report["errors"].append(name + (": " + detail if detail else "")) def load(path, label, expected_sha256): try: raw = path.read_bytes() except OSError as exc: check(label + "_readable", False, type(exc).__name__) return None digest = hashlib.sha256(raw).hexdigest() report["files"][label] = { "name": path.name, "bytes": len(raw), "sha256": digest, "expected_sha256": expected_sha256, } check(label + "_readable", True) check(label + "_sha256_matches", digest == expected_sha256) return raw source_raw = load(source_path, "source", SOURCE_SHA256) csv_raw = load(csv_path, "csv", CSV_SHA256) if source_raw is None or csv_raw is None: return report check("source_byte_count", len(source_raw) == 112137) try: document = json.loads(source_raw.decode("utf-8")) except (UnicodeError, ValueError) as exc: check("source_valid_json", False, type(exc).__name__) return report check("source_valid_json", True) check("source_object", isinstance(document, dict)) if not isinstance(document, dict): return report check("source_top_level_keys", set(document) == {"name", "matches"}) check("source_competition_name", document.get("name") == "Primera División de España 2019/20") matches = document.get("matches") check("matches_is_list", isinstance(matches, list)) if not isinstance(matches, list): return report teams = set() pairs = Counter() invalid_keys = [] invalid_teams = [] invalid_ft = [] counts = {"matches": len(matches), "home_wins": 0, "draws": 0, "away_wins": 0} for index, match in enumerate(matches): if not isinstance(match, dict) or not REQUIRED_MATCH_KEYS.issubset(match): invalid_keys.append(index) if not isinstance(match, dict): invalid_teams.append(index) invalid_ft.append(index) continue home, away = match.get("team1"), match.get("team2") valid_teams = ( isinstance(home, str) and isinstance(away, str) and bool(home.strip()) and bool(away.strip()) and home == home.strip() and away == away.strip() and home != away ) if valid_teams: teams.update((home, away)) pairs[(home, away)] += 1 else: invalid_teams.append(index) score = match.get("score") ft = score.get("ft") if isinstance(score, dict) else None valid_ft = ( isinstance(ft, list) and len(ft) == 2 and all(type(value) is int and value >= 0 for value in ft) ) if not valid_ft: invalid_ft.append(index) continue if ft[0] > ft[1]: counts["home_wins"] += 1 elif ft[0] == ft[1]: counts["draws"] += 1 else: counts["away_wins"] += 1 duplicates = [ {"home": home, "away": away, "occurrences": number} for (home, away), number in sorted(pairs.items()) if number > 1 ] expected_pairs = {(home, away) for home in teams for away in teams if home != away} missing_pairs = sorted(expected_pairs.difference(pairs)) report["computed"] = { **counts, "teams": len(teams), "team_names": sorted(teams), "ordered_pairs": len(pairs), "duplicate_pair_count": len(duplicates), "duplicate_match_count": sum(number - 1 for number in pairs.values() if number > 1), "duplicate_pairs": duplicates, "missing_ordered_pair_count": len(missing_pairs), "missing_ordered_pairs": [list(pair) for pair in missing_pairs], "missing_or_invalid_ft_count": len(invalid_ft), "invalid_match_key_indices": invalid_keys, "invalid_team_indices": invalid_teams, "missing_or_invalid_ft_indices": invalid_ft, } check("required_match_keys", not invalid_keys) check("team_names_valid_and_distinct", not invalid_teams) check("all_ft_are_two_nonnegative_integers", not invalid_ft) check("match_count_380", len(matches) == 380) check("team_count_20", len(teams) == 20) check("ordered_pair_count_380", len(pairs) == 380) check("no_duplicate_pairs", not duplicates) check("complete_home_away_pair_set", set(pairs) == expected_pairs) check("outcome_counts_sum_to_matches", sum(counts[key] for key in COUNT_KEYS[1:]) == len(matches)) try: reader = csv.DictReader(io.StringIO(csv_raw.decode("utf-8-sig"), newline="")) rows = list(reader) except (UnicodeError, csv.Error) as exc: check("csv_valid", False, type(exc).__name__) return report check("csv_valid", True) check("csv_expected_columns", reader.fieldnames == CSV_COLUMNS) check("csv_row_count_20", len(rows) == 20) check("csv_row_shapes", all(set(row) == set(CSV_COLUMNS) and None not in row.values() for row in rows)) target_rows = [row for row in rows if row.get("league") == "LaLiga" and row.get("season") == "2019-20"] report["comparison"] = { "league": "LaLiga", "season": "2019-20", "csv_total_rows": len(rows), "target_rows_found": len(target_rows), "rows_compared": 0, } check("csv_target_row_unique", len(target_rows) == 1) if len(target_rows) == 1: target = target_rows[0] try: published = {key: int(target[key]) for key in COUNT_KEYS} valid_numbers = all(value >= 0 for value in published.values()) except (KeyError, TypeError, ValueError): published = None valid_numbers = False check("csv_target_nonnegative_integer_counts", valid_numbers) if valid_numbers: report["comparison"]["published_counts"] = published report["comparison"]["rows_compared"] = 1 report["comparison"]["differences_computed_minus_published"] = { key: counts[key] - published[key] for key in COUNT_KEYS } check("source_counts_match_published_row", counts == published) check("published_outcome_counts_sum", sum(published[key] for key in COUNT_KEYS[1:]) == published["matches"]) report["status"] = "PASS" if all(report["checks"].values()) and not report["errors"] else "FAIL" return report def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--source", type=Path, default=BASE / "fuente-laliga-2019-20.json", help="Local fixed-source JSON") parser.add_argument("--csv", type=Path, default=BASE / "resultados-liga-temporada.csv", help="Local published aggregate snapshot") args = parser.parse_args() report = verify(args.source, args.csv) print(json.dumps(report, ensure_ascii=False, indent=2, sort_keys=True)) return 0 if report["status"] == "PASS" else 1 if __name__ == "__main__": sys.exit(main())