"""
PageSpeed Insights (Lighthouse) integration.
Uses a simple API key — get one from Google Cloud Console
(APIs & Services > Credentials > Create API Key), then restrict it
to the "PageSpeed Insights API".
"""
import requests

PSI_ENDPOINT = 'https://www.googleapis.com/pagespeedonline/v5/runPagespeed'


def fetch_psi_score(api_key, url, strategy='mobile'):
    """
    strategy: 'mobile' or 'desktop'
    Returns core scores + Core Web Vitals, or None on failure.
    """
    params = {
        'url': url,
        'key': api_key,
        'strategy': strategy,
        'category': ['PERFORMANCE', 'ACCESSIBILITY', 'BEST_PRACTICES', 'SEO'],
    }
    try:
        resp = requests.get(PSI_ENDPOINT, params=params, timeout=60)
        resp.raise_for_status()
        data = resp.json()
    except requests.RequestException as e:
        return {'error': str(e)}

    categories = data.get('lighthouseResult', {}).get('categories', {})
    audits = data.get('lighthouseResult', {}).get('audits', {})

    def score_pct(cat_key):
        cat = categories.get(cat_key)
        if not cat or cat.get('score') is None:
            return None
        return round(cat['score'] * 100)

    def audit_val(audit_key):
        a = audits.get(audit_key, {})
        return a.get('numericValue')

    lcp = audit_val('largest-contentful-paint')
    cls = audit_val('cumulative-layout-shift')
    inp = audit_val('interaction-to-next-paint') or audit_val('total-blocking-time')

    return {
        'performance': score_pct('performance'),
        'accessibility': score_pct('accessibility'),
        'best_practices': score_pct('best-practices'),
        'seo': score_pct('seo'),
        'lcp': round(lcp / 1000, 2) if lcp else None,   # ms -> s
        'cls': round(cls, 3) if cls is not None else None,
        'inp': round(inp, 0) if inp else None,          # ms
    }
