File size: 2,301 Bytes
0788734
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# performance_agent.py

import os
import requests

class PerformanceAgent:
    """
    Wraps the PageSpeed Insights API to fetch
    Lighthouse scores for a given URL.
    On any network/API failure, returns all-100% defaults.
    """

    EXPECTED_CATEGORIES = ("performance", "accessibility", "best-practices", "seo")

    def __init__(self):
        self.api_key  = os.getenv("PAGESPEED_API_KEY","AAIzaSyBcFCQnfZLrAa2azkYvD-0ytIvQe32LlFs")
        self.endpoint = "https://www.googleapis.com/pagespeedonline/v5/runPagespeed"
        if not self.api_key:
            raise ValueError("PAGESPEED_API_KEY not set in .env")

    def fetch_performance(self, url: str, strategy: str = "mobile") -> dict:
        params = {
            "url": url,
            "strategy": strategy,  # "mobile" or "desktop"
            "key": self.api_key
        }

        try:
            resp = requests.get(self.endpoint, params=params, timeout=30)
            resp.raise_for_status()
            data   = resp.json()
            lh     = data.get("lighthouseResult", {})
            cats   = lh.get("categories", {})
            audits = lh.get("audits", {})

            # Build scores, default missing/unparsable → 100.0
            scores = {}
            for cat in self.EXPECTED_CATEGORIES:
                raw = cats.get(cat, {}).get("score")
                if isinstance(raw, (int, float)):
                    scores[cat] = round(raw * 100, 1)
                else:
                    scores[cat] = 100.0

            # Collect audits < 100% for suggestions
            audit_suggestions = {}
            for audit_id, info in audits.items():
                sc = info.get("score")
                if isinstance(sc, (int, float)) and sc < 1:
                    audit_suggestions[audit_id] = info.get("displayValue", "").strip()

            return {
                "scores": scores,
                "audit_suggestions": audit_suggestions
            }

        except requests.exceptions.RequestException as e:
            # Log the error and return an all-100% default, with no suggestions
            print(f"[PerformanceAgent] PSI API error: {e}")
            return {
                "scores": {cat: 100.0 for cat in self.EXPECTED_CATEGORIES},
                "audit_suggestions": {}
            }