Spaces:
Sleeping

File size: 5,543 Bytes
81163d9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
import logging
from datetime import datetime, timezone, timedelta
from typing import Optional
from app.core.supabase_client import get_supabase  # ← was: from app.core.supabase_client import supabase

logger = logging.getLogger(__name__)

_memory_cache: dict[str, dict] = {}


def _make_cache_key(league: str) -> str:
    return f"upcoming_{league}"


def _calc_ttl_hours(league: str = "epl") -> int:
    now     = datetime.now(timezone.utc)
    weekday = now.weekday()
    if weekday in (1, 2, 5, 6):
        return 1
    return 6


def get_cached(league: str = "epl") -> Optional[list]:
    key = _make_cache_key(league)
    now = datetime.now(timezone.utc)

    # ── 1. Memory cache ───────────────────────────────────────────────────────
    if key in _memory_cache:
        entry = _memory_cache[key]
        if entry["expires_at"] > now:
            logger.info(f"⚡ Memory cache hit for {key} "
                        f"(expires in {int((entry['expires_at'] - now).seconds / 60)} min)")
            return entry["payload"]
        else:
            logger.info(f"⏰ Memory cache expired for {key}")
            del _memory_cache[key]

    # ── 2. Supabase cache ─────────────────────────────────────────────────────
    try:
        supabase = get_supabase()   # ← call the function each time needed
        result = (
            supabase.table("predictions_cache")
            .select("*")
            .eq("cache_key", key)
            .gt("expires_at", now.isoformat())
            .execute()
        )
        if result.data:
            row        = result.data[0]
            expires_at = datetime.fromisoformat(row["expires_at"])

            _memory_cache[key] = {
                "payload":    row["payload"],
                "expires_at": expires_at,
            }

            supabase.table("predictions_cache").update(
                {"hit_count": row["hit_count"] + 1}
            ).eq("cache_key", key).execute()

            logger.info(f"🗄️  Supabase cache hit for {key} "
                        f"(expires in {int((expires_at - now).seconds / 60)} min, "
                        f"hit #{row['hit_count'] + 1})")
            return row["payload"]

    except Exception as e:
        logger.warning(f"Cache read failed for {key}: {e}")

    return None


def set_cache(league: str, payload: list) -> None:
    key        = _make_cache_key(league)
    now        = datetime.now(timezone.utc)
    ttl_hours  = _calc_ttl_hours(league)
    expires_at = now + timedelta(hours=ttl_hours)
    fixture_ids = [str(f.get("fixture_id", "")) for f in payload]

    _memory_cache[key] = {
        "payload":    payload,
        "expires_at": expires_at,
    }

    try:
        supabase = get_supabase()   # ← call the function each time needed
        supabase.table("predictions_cache").upsert({
            "cache_key":   key,
            "league":      league,
            "payload":     payload,
            "fixture_ids": fixture_ids,
            "fetched_at":  now.isoformat(),
            "expires_at":  expires_at.isoformat(),
            "hit_count":   0,
        }, on_conflict="cache_key").execute()

        logger.info(f"💾 Cache saved for {key} — "
                    f"{len(payload)} fixtures, TTL {ttl_hours}h "
                    f"(expires {expires_at.strftime('%H:%M UTC')})")
    except Exception as e:
        logger.warning(f"Cache write failed for {key}: {e}")


def invalidate_cache(league: str) -> None:
    key = _make_cache_key(league)

    if key in _memory_cache:
        del _memory_cache[key]

    try:
        supabase = get_supabase()   # ← call the function each time needed
        supabase.table("predictions_cache").delete().eq("cache_key", key).execute()
        logger.info(f"🗑️  Cache invalidated for {key}")
    except Exception as e:
        logger.warning(f"Cache invalidation failed for {key}: {e}")


def get_cache_status(league: str) -> dict:
    key = _make_cache_key(league)
    now = datetime.now(timezone.utc)

    if key in _memory_cache:
        entry      = _memory_cache[key]
        expires_in = int((entry["expires_at"] - now).seconds / 60)
        return {
            "source":          "memory",
            "cached":          True,
            "fixture_count":   len(entry["payload"]),
            "expires_in_mins": expires_in,
        }

    try:
        supabase = get_supabase()   # ← call the function each time needed
        result = (
            supabase.table("predictions_cache")
            .select("fetched_at, expires_at, hit_count, fixture_ids")
            .eq("cache_key", key)
            .execute()
        )
        if result.data:
            row        = result.data[0]
            expires_at = datetime.fromisoformat(row["expires_at"])
            is_fresh   = expires_at > now
            return {
                "source":          "supabase",
                "cached":          is_fresh,
                "fixture_count":   len(row["fixture_ids"]),
                "fetched_at":      row["fetched_at"],
                "expires_in_mins": int((expires_at - now).seconds / 60) if is_fresh else 0,
                "total_hits":      row["hit_count"],
            }
    except Exception as e:
        logger.warning(f"Cache status check failed: {e}")

    return {"cached": False, "source": None}