Skip to content

Universal SEO skill for Claude Code. 26 sub-skills + 19 sub-agents covering technical SEO, E-E-A-T, schema, GEO/AEO, agent readiness (Lighthouse Agentic Browsing, WebMCP, llms.txt), backlinks, local SEO, e-commerce, international SEO, Google APIs, and PDF/Excel reporting. 9 optional extensions for live SEO data.

feat: v1.7.0 - Google SEO APIs, PDF reports, security hardening

Daniel7db6bac53170
diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json
index 93a87c4..81c7946 100644
--- a/.claude-plugin/marketplace.json
+++ b/.claude-plugin/marketplace.json
@@ -16,9 +16,9 @@
"homepage": "https://github.com/AgriciDaniel/claude-seo",
"repository": "https://github.com/AgriciDaniel/claude-seo",
"license": "MIT",
- "keywords": ["seo", "technical-seo", "e-e-a-t", "schema-markup", "local-seo", "geo", "ai-search"],
+ "keywords": ["seo", "technical-seo", "e-e-a-t", "schema-markup", "local-seo", "geo", "ai-search", "google-api", "search-console", "pagespeed", "crux"],
"category": "seo",
- "tags": ["seo", "audit", "technical", "content", "schema", "local", "geo"]
+ "tags": ["seo", "audit", "technical", "content", "schema", "local", "geo", "google-api"]
}
]
}
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json
index c526474..8d31326 100644
--- a/.claude-plugin/plugin.json
+++ b/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "claude-seo",
- "version": "1.6.1",
+ "version": "1.7.0",
"description": "Comprehensive SEO analysis skill for Claude Code. Covers technical SEO, content quality (E-E-A-T), schema markup, image optimization, sitemap architecture, AI search optimization (GEO), local SEO (GBP, citations, reviews, map pack), maps intelligence, and strategic planning across all industries.",
"author": {
"name": "AgriciDaniel",
@@ -21,6 +21,10 @@
"ai-search",
"sitemap",
"image-optimization",
- "hreflang"
+ "hreflang",
+ "google-search-console",
+ "pagespeed",
+ "crux",
+ "ga4"
]
}
diff --git a/.gitignore b/.gitignore
index 89aa245..42c8b75 100644
--- a/.gitignore
+++ b/.gitignore
@@ -31,6 +31,16 @@ venv/
env/
.env/
+# Secrets and credentials (NEVER commit these)
+.env
+.env.*
+*.env
+**/.env
+**/client_secret*.json
+**/service_account*.json
+**/oauth-token.json
+**/.google-token.json
+
# Node (if any)
node_modules/
@@ -86,6 +96,10 @@ seo audit demo.gif
seo command demo.gif
.github-audit/
+# Generated Google SEO reports
+Google-SEO-Report-*.html
+Google-SEO-Report-*.pdf
+
# Site-specific analysis outputs
LOCAL-SEO-ANALYSIS-*.md
LOCAL-SEO-ANALYSIS-*.html
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 4ad3d68..95409a6 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,34 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
+## [1.7.0] - 2026-03-28
+
+### Added
+- **Google SEO APIs skill**: `skills/seo-google/SKILL.md` with 21 commands across 4 credential tiers
+- **Google subagent**: `agents/seo-google.md` for enriched audit data (CWV field data, indexation status, organic traffic)
+- **11 Python scripts**: google_auth.py, gsc_query.py, gsc_inspect.py, pagespeed_check.py, crux_history.py, indexing_notify.py, ga4_report.py, google_report.py, youtube_search.py, nlp_analyze.py, keyword_planner.py
+- **10 reference files**: auth-setup.md, search-console-api.md, pagespeed-crux-api.md, indexing-api.md, ga4-data-api.md, youtube-api.md, nlp-api.md, keyword-planner-api.md, supplementary-apis.md, rate-limits-quotas.md
+- **PDF report generator**: `scripts/google_report.py` with enterprise A4 template, WeasyPrint + matplotlib charts, post-generation quality review
+- **OAuth web credential flow**: Browser-based auth with localhost:8085 callback, token refresh, manual code exchange fallback
+- **4-tier credential system**: Tier 0 (API key: PSI/CrUX), Tier 1 (+OAuth/SA: GSC/Indexing), Tier 2 (+GA4), Tier 3 (+Ads Keyword Planner)
+- **Python dependencies**: google-api-python-client, google-auth, google-auth-oauthlib, google-auth-httplib2, google-analytics-data, matplotlib, weasyprint
+
+### Security
+- SSRF protection: `validate_url()` blocks private IPs, loopback, and GCP metadata endpoints in all Google API scripts
+- `.gitignore` hardened with 8 credential patterns: `.env`, `client_secret*.json`, `oauth-token.json`, `service_account*.json`
+- OAuth tokens no longer store `client_secret` (reads from client_secret.json file only)
+- Removed hardcoded user paths from all scripts (mobile_analysis.py, capture scripts)
+
+### Changed
+- Sub-skill count: 14 -> 15 core (+ 2 extensions)
+- Subagent count: 9 -> 10 core (+ 2 extension) with conditional Google API spawning
+- seo-audit spawns seo-google agent when Google API credentials detected
+- seo-technical and seo-performance can use CrUX field data when available
+- Report Generation Rules added to CLAUDE.md with color palette, dependency, and cross-skill enforcement
+- README updated with Google APIs, local SEO, maps, and PDF report features
+
+---
+
## [1.6.1] - 2026-03-27
### Added
diff --git a/CLAUDE.md b/CLAUDE.md
index f38fedb..8c80245 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -4,8 +4,8 @@
This repository contains **Claude SEO**, a Tier 4 Claude Code skill for comprehensive
SEO analysis across all industries. It follows the Agent Skills open standard and the
-3-layer architecture (directive, orchestration, execution). 14 core sub-skills (+ 2
-extensions), 9 core subagents (+ 2 extension agents), and an extensible reference
+3-layer architecture (directive, orchestration, execution). 15 core sub-skills (+ 2
+extensions), 10 core subagents (+ 2 extension agents), and an extensible reference
system cover technical SEO, content quality,
schema markup, image optimization, sitemap architecture, AI search optimization,
local SEO (GBP, citations, reviews, map pack), and maps intelligence (geo-grid
@@ -17,7 +17,7 @@ rank tracking, GBP auditing, review intelligence, competitor radius mapping).
claude-seo/
CLAUDE.md # Project instructions (this file)
.claude-plugin/
- plugin.json # Plugin manifest (v1.6.1)
+ plugin.json # Plugin manifest (v1.7.0)
marketplace.json # Marketplace catalog for distribution
skills/ # 17 skills (auto-discovered)
seo/ # Main orchestrator skill
@@ -37,11 +37,14 @@ claude-seo/
seo-programmatic/SKILL.md # Programmatic SEO at scale
seo-competitor-pages/SKILL.md # Competitor comparison pages
seo-hreflang/SKILL.md # International SEO / hreflang
+ seo-google/ # Google SEO APIs
+ SKILL.md
+ references/ # API reference files (7 files)
seo-dataforseo/SKILL.md # Live SEO data via DataForSEO MCP
seo-image-gen/ # AI image generation for SEO assets
SKILL.md
references/ # Image gen reference files (7 files)
- agents/ # 11 subagents (auto-discovered)
+ agents/ # 12 subagents (auto-discovered)
seo-technical.md # Crawlability, indexability, security
seo-content.md # E-E-A-T, readability, thin content
seo-schema.md # Structured data validation
@@ -51,6 +54,7 @@ claude-seo/
seo-geo.md # AI crawler access, GEO, citability
seo-local.md # GBP, NAP, citations, reviews, local schema
seo-maps.md # Geo-grid, GBP audit, reviews, competitor radius
+ seo-google.md # Google API analyst (CrUX, GSC, GA4)
seo-dataforseo.md # DataForSEO data analyst
seo-image-gen.md # SEO image audit analyst
hooks/ # Quality gate hooks
@@ -67,7 +71,7 @@ claude-seo/
| Command | Purpose |
|---------|---------|
-| `/seo audit <url>` | Full site audit with 9 parallel subagents |
+| `/seo audit <url>` | Full site audit with 10 parallel subagents |
| `/seo page <url>` | Deep single-page analysis |
| `/seo technical <url>` | Technical SEO audit (9 categories) |
| `/seo content <url>` | E-E-A-T and content quality analysis |
@@ -81,6 +85,7 @@ claude-seo/
| `/seo local <url>` | Local SEO analysis (GBP, citations, reviews, map pack) |
| `/seo maps [command] [args]` | Maps intelligence (geo-grid, GBP audit, reviews, competitors) |
| `/seo hreflang <url>` | International SEO / hreflang audit |
+| `/seo google [command] [url]` | Google SEO APIs (GSC, PageSpeed, CrUX, Indexing, GA4) |
| `/seo image-gen [use-case] <desc>` | AI image generation for SEO assets (extension) |
## Development Rules
@@ -93,6 +98,21 @@ claude-seo/
- Python dependencies install into `~/.claude/skills/seo/.venv/`
- Test with `python -m pytest tests/` after changes (if applicable)
+## Report Generation Rules
+
+- **All SEO reports must use `scripts/google_report.py`** as the canonical report generator
+- **Dependencies**: `matplotlib>=3.8.0` (charts) + `weasyprint>=61.0` (HTML-to-PDF), both in `requirements.txt`
+- **Format**: A4 PDF via WeasyPrint + matplotlib charts at 200 DPI
+- **Style**: Clean white title page with navy (#1e3a5f) accent, Times New Roman body font
+- **Color palette**: Navy #1e3a5f (headers), dark gold #b8860b (accents), forest green #2d6a4f (pass), warm amber #d4740e (warnings), deep red #c53030 (fail), warm cream #faf9f7 (backgrounds)
+- **Structure**: Title page → TOC with scores → Executive Summary → Data sections → Recommendations → Methodology
+- **Charts**: 85% width, max-height 120mm, figure captions on every chart, saved to `charts/` at 200 DPI
+- **No `page-break-inside: avoid`** on any element (causes white gaps in WeasyPrint)
+- **Post-generation review**: `_review_pdf()` runs automatically, checking for empty images, thin sections, duplicates
+- **Before presenting any PDF to the user**: verify the review passes (`"status": "PASS"`)
+- **Cross-skill enforcement**: After completing ANY analysis command (audit, page, technical, content, schema, geo, local, maps), offer: "Generate a PDF report? Use `/seo google report`"
+- **Google logo** appears on title page when using Google API data ("Powered by Google APIs")
+
## Ecosystem
Part of the Claude Code skill family:
diff --git a/README.md b/README.md
index ecefd3c..6799594 100644
--- a/README.md
+++ b/README.md
@@ -1,10 +1,10 @@
-<!-- Updated: 2026-03-06 -->
+<!-- Updated: 2026-03-28 -->
![Claude SEO](screenshots/cover-image.jpeg)
# Claude SEO - SEO Audit Skill for Claude Code
-Comprehensive SEO analysis skill for Claude Code. Covers technical SEO, on-page analysis, content quality (E-E-A-T), schema markup, image optimization, sitemap architecture, AI search optimization (GEO), and strategic planning.
+Comprehensive SEO analysis skill for Claude Code. Covers technical SEO, on-page analysis, content quality (E-E-A-T), schema markup, image optimization, sitemap architecture, AI search optimization (GEO), local SEO, maps intelligence, Google SEO APIs (Search Console, PageSpeed, CrUX, GA4), PDF report generation, and strategic planning.
![SEO Command Demo](screenshots/seo-command-demo.gif)
@@ -113,7 +113,11 @@ claude
| `/seo plan <type>` | Strategic SEO planning (saas, local, ecommerce, publisher, agency) |
| `/seo programmatic <url>` | Programmatic SEO analysis and planning |
| `/seo competitor-pages <url>` | Competitor comparison page generation |
+| `/seo local <url>` | Local SEO analysis (GBP, citations, reviews, map pack) |
+| `/seo maps [command]` | Maps intelligence (geo-grid, GBP audit, reviews, competitors) |
| `/seo hreflang <url>` | Hreflang/i18n SEO audit and generation |
+| `/seo google [command] [url]` | Google SEO APIs (GSC, PageSpeed, CrUX, Indexing, GA4) |
+| `/seo google report [type]` | Generate PDF/HTML report with charts (cwv-audit, gsc-performance, full) |
### `/seo programmatic [url|plan]`
**Programmatic SEO Analysis & Planning**
@@ -183,6 +187,28 @@ New for 2026 - optimize for:
- Perplexity
- Other AI-powered search
+### Google SEO APIs (New in v1.7.0)
+Direct integration with Google's SEO data:
+- **PageSpeed Insights + CrUX**: Lab and field Core Web Vitals data
+- **Search Console**: Top queries, URL inspection, sitemap status
+- **Indexing API**: Notify Google of new/updated/removed URLs
+- **GA4**: Organic traffic, top landing pages, device/country breakdown
+- **PDF Reports**: Enterprise A4 reports with charts via WeasyPrint + matplotlib
+
+4-tier credential system — get value at every level:
+| Tier | Auth | APIs |
+|------|------|------|
+| 0 | API key | PSI, CrUX, CrUX History |
+| 1 | + OAuth/SA | + GSC, URL Inspection, Indexing |
+| 2 | + GA4 config | + GA4 organic traffic |
+| 3 | + Ads token | + Keyword Planner |
+
+### Local SEO & Maps Intelligence (New in v1.6.0)
+- Google Business Profile optimization
+- NAP consistency auditing
+- Citation and review analysis
+- Geo-grid rank tracking and competitor radius mapping
+
### Quality Gates
- Warning at 30+ location pages
- Hard stop at 50+ location pages
@@ -192,9 +218,9 @@ New for 2026 - optimize for:
## Architecture
```
-~/.claude/skills/seo/ # Main skill
-~/.claude/skills/seo-*/ # Sub-skills (12 total)
-~/.claude/agents/seo-*.md # Subagents (7 total)
+~/.claude/skills/seo/ # Main orchestrator skill
+~/.claude/skills/seo-*/ # Sub-skills (15 + 2 extensions)
+~/.claude/agents/seo-*.md # Subagents (10 + 2 extensions)
```
### Video & Live Schema (New)
@@ -219,6 +245,7 @@ See `schema/templates.json` for ready-to-use JSON-LD snippets.
- Python 3.10+
- Claude Code CLI
- Optional: Playwright for screenshots
+- Optional: Google API credentials for enriched data (see `/seo google setup`)
## Uninstall
diff --git a/agents/seo-google.md b/agents/seo-google.md
new file mode 100644
index 0000000..c737e51
--- /dev/null
+++ b/agents/seo-google.md
@@ -0,0 +1,69 @@
+---
+name: seo-google
+description: Google SEO API analyst. Fetches CWV field data via CrUX, indexation status via GSC, and organic traffic via GA4 for enriched audit data.
+model: sonnet
+maxTurns: 15
+tools: Read, Bash, Write, Glob, Grep # Write needed for report/data file output
+---
+
+You are a Google SEO API data analyst. When delegated tasks during an SEO audit:
+
+1. Check credentials: `python scripts/google_auth.py --check --json`
+2. Determine tier (0 = API key, 1 = + service account, 2 = + GA4)
+3. Execute tier-appropriate analysis
+4. Format output to match claude-seo conventions
+
+## Tier-Based Workflow
+
+### Tier 0 (API Key Only)
+- Run PSI + CrUX on homepage: `python scripts/pagespeed_check.py <url> --json`
+- Run CrUX History for origin: `python scripts/crux_history.py <origin> --origin --json`
+- Report CWV field data with traffic-light ratings
+
+### Tier 1 (+ Service Account)
+- All Tier 0 checks
+- GSC top queries/pages (28 days): `python scripts/gsc_query.py --property <prop> --json`
+- URL Inspection on homepage + key pages: `python scripts/gsc_inspect.py <url> --json`
+- GSC sitemap status: `python scripts/gsc_query.py sitemaps --property <prop> --json`
+
+### Tier 2 (Full)
+- All Tier 1 checks
+- GA4 organic traffic (28 days): `python scripts/ga4_report.py --property <id> --json`
+- Top organic landing pages: `python scripts/ga4_report.py --property <id> --report top-pages --json`
+
+## Core Web Vitals Thresholds
+
+| Metric | Good | Needs Improvement | Poor |
+|--------|------|-------------------|------|
+| LCP | ≤ 2,500ms | 2,500-4,000ms | > 4,000ms |
+| INP | ≤ 200ms | 200-500ms | > 500ms |
+| CLS | ≤ 0.1 | 0.1-0.25 | > 0.25 |
+
+INP replaced FID on March 12, 2024. Never reference FID.
+
+## Output Format
+
+Match existing claude-seo patterns:
+- Tables for metrics with traffic-light ratings
+- Scores as XX/100
+- Priority: Critical > High > Medium > Low
+- Note data source as "Google API (field data)" to distinguish from static analysis
+- Include data freshness notes (CrUX: 28-day rolling, GSC: 2-3 day lag, GA4: 1 day lag)
+
+## Report Generation (MANDATORY)
+
+After completing data collection at any tier, ALWAYS offer to generate a PDF report.
+The report uses the enterprise template: white cover, navy accents, Times New Roman, charts at 85% width, Google logo on title page. No page-break-inside: avoid (causes white gaps).
+
+```bash
+python scripts/google_report.py --type full --data data.json --domain DOMAIN --format pdf --json
+```
+Report types: `cwv-audit`, `gsc-performance`, `indexation`, `full`.
+Before presenting: verify `"review": {"status": "PASS"}` in the JSON output.
+
+## Error Handling
+
+- If credentials are missing, report which tier is available and what can still be checked
+- If CrUX returns 404, note insufficient Chrome traffic and fall back to PSI lab data
+- If GSC returns 403, report the service account email and instruct on adding permissions
+- Never fail silently -- always report what succeeded and what failed
diff --git a/agents/seo-performance.md b/agents/seo-performance.md
index 2261c7e..7f8ef59 100644
--- a/agents/seo-performance.md
+++ b/agents/seo-performance.md
@@ -71,6 +71,15 @@ curl "https://www.googleapis.com/pagespeedonline/v5/runPagespeed?url=URL&key=API
npx lighthouse URL --output json
```
+## Google API Integration (Optional)
+
+If Google API credentials are configured, prefer CrUX field data over Lighthouse lab data for CWV assessment:
+```bash
+python scripts/pagespeed_check.py URL --json
+python scripts/crux_history.py URL --json
+```
+Field data (28-day Chrome user average) is more representative than lab data (single Lighthouse run). Use lab data as fallback when CrUX returns 404 (insufficient traffic).
+
## Output Format
Provide:
diff --git a/agents/seo-technical.md b/agents/seo-technical.md
index b4f4416..7d44ddb 100644
--- a/agents/seo-technical.md
+++ b/agents/seo-technical.md
@@ -3,7 +3,7 @@ name: seo-technical
description: Technical SEO specialist. Analyzes crawlability, indexability, security, URL structure, mobile optimization, Core Web Vitals, and JavaScript rendering.
model: sonnet
maxTurns: 20
-tools: Read, Bash, Write, Glob, Grep
+tools: Read, Bash, Write, Glob, Grep # Write needed for report/data file output
---
You are a Technical SEO specialist. When given a URL or set of URLs:
diff --git a/pyproject.toml b/pyproject.toml
index dbdcf3d..4fd9b84 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -1,6 +1,6 @@
[project]
name = "claude-seo"
-version = "1.5.0"
+version = "1.7.0"
description = "Comprehensive SEO analysis skill for Claude Code"
requires-python = ">=3.11"
license = "MIT"
diff --git a/requirements.txt b/requirements.txt
index 29a89bd..eb32bec 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -9,3 +9,14 @@ playwright>=1.56.0,<2.0.0 # CVE-2025-59288 fix (macOS)
Pillow>=12.1.0,<13.0.0 # CVE-2025-48379 fix
urllib3>=2.6.3,<3.0.0 # CRITICAL: CVE-2026-21441 (CVSS 8.9), CVE-2025-66418
validators>=0.22.0,<1.0.0 # No known CVEs
+
+# Report generation (for seo-google PDF reports)
+matplotlib>=3.8.0,<4.0.0 # No known CVEs
+weasyprint>=61.0,<70.0 # No known CVEs
+
+# Google API dependencies (for seo-google skill)
+google-api-python-client>=2.100.0,<3.0.0 # No known CVEs
+google-auth>=2.20.0,<3.0.0 # No known CVEs
+google-auth-oauthlib>=1.0.0,<2.0.0 # No known CVEs
+google-auth-httplib2>=0.2.0,<1.0.0 # No known CVEs
+google-analytics-data>=0.18.0,<1.0.0 # No known CVEs
diff --git a/scripts/crux_history.py b/scripts/crux_history.py
new file mode 100644
index 0000000..0f41454
--- /dev/null
+++ b/scripts/crux_history.py
@@ -0,0 +1,321 @@
+#!/usr/bin/env python3
+"""
+CrUX History API for Core Web Vitals trends over time.
+
+Fetches up to 25 weekly data points from the Chrome UX Report History API
+and identifies improving, stable, or degrading trends per metric.
+
+Usage:
+ python crux_history.py https://example.com
+ python crux_history.py https://example.com --form-factor PHONE --json
+ python crux_history.py https://example.com --origin
+"""
+
+import argparse
+import json
+import sys
+from typing import Optional
+from urllib.parse import urlparse
+
+try:
+ import requests
+except ImportError:
+ print("Error: requests library required. Install with: pip install requests")
+ sys.exit(1)
+
+try:
+ from google_auth import get_api_key, validate_url
+except ImportError:
+ import os
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+ from google_auth import get_api_key, validate_url
+
+CRUX_HISTORY_ENDPOINT = "https://chromeuxreport.googleapis.com/v1/records:queryHistoryRecord"
+
+CWV_THRESHOLDS = {
+ "largest_contentful_paint": {"good": 2500, "poor": 4000, "label": "LCP", "unit": "ms"},
+ "interaction_to_next_paint": {"good": 200, "poor": 500, "label": "INP", "unit": "ms"},
+ "cumulative_layout_shift": {"good": 0.1, "poor": 0.25, "label": "CLS", "unit": ""},
+ "first_contentful_paint": {"good": 1800, "poor": 3000, "label": "FCP", "unit": "ms"},
+ "experimental_time_to_first_byte": {"good": 800, "poor": 1800, "label": "TTFB", "unit": "ms"},
+}
+
+
+def query_history(
+ url_or_origin: str,
+ api_key: str,
+ form_factor: Optional[str] = None,
+) -> dict:
+ """
+ Query CrUX History API for weekly CWV trends.
+
+ Args:
+ url_or_origin: Full URL or origin.
+ api_key: Google API key.
+ form_factor: DESKTOP, PHONE, or TABLET. None for all.
+
+ Returns:
+ Dictionary with metrics timeseries, collection periods, and trend analysis.
+ """
+ result = {
+ "target": url_or_origin,
+ "form_factor": form_factor or "ALL",
+ "metrics": {},
+ "collection_periods": [],
+ "trends": {},
+ "error": None,
+ }
+
+ if not validate_url(url_or_origin):
+ result["error"] = "Invalid URL. Only http/https URLs to public hosts are accepted."
+ return result
+
+ parsed = urlparse(url_or_origin)
+ is_origin = parsed.path in ("", "/") and not parsed.query
+
+ body = {}
+ if is_origin:
+ body["origin"] = f"{parsed.scheme}://{parsed.netloc}"
+ else:
+ body["url"] = url_or_origin
+
+ if form_factor:
+ body["formFactor"] = form_factor.upper()
+
+ try:
+ resp = requests.post(
+ f"{CRUX_HISTORY_ENDPOINT}?key={api_key}",
+ json=body,
+ timeout=30,
+ )
+
+ if resp.status_code == 404:
+ target_type = "origin" if is_origin else "URL"
+ result["error"] = (
+ f"No CrUX history data for this {target_type}. "
+ "Insufficient Chrome traffic volume for eligibility."
+ )
+ return result
+
+ if resp.status_code == 429:
+ result["error"] = "CrUX API rate limit exceeded (150 QPM shared). Wait and retry."
+ return result
+
+ resp.raise_for_status()
+ data = resp.json()
+ except requests.exceptions.RequestException as e:
+ result["error"] = f"CrUX History API request failed: {e}"
+ return result
+
+ record = data.get("record", {})
+
+ # Collection periods
+ periods = record.get("collectionPeriods", [])
+ for period in periods:
+ first = period.get("firstDate", {})
+ last = period.get("lastDate", {})
+ result["collection_periods"].append({
+ "first": f"{first.get('year')}-{first.get('month', 0):02d}-{first.get('day', 0):02d}",
+ "last": f"{last.get('year')}-{last.get('month', 0):02d}-{last.get('day', 0):02d}",
+ })
+
+ # Metrics timeseries
+ for metric_name, metric_data in record.get("metrics", {}).items():
+ if metric_name not in CWV_THRESHOLDS:
+ continue
+
+ thresholds = CWV_THRESHOLDS[metric_name]
+ p75s_data = metric_data.get("percentilesTimeseries", {})
+ p75s_raw = p75s_data.get("p75s", [])
+
+ # Parse p75 values (CLS is string-encoded)
+ p75s = []
+ for val in p75s_raw:
+ if val is None:
+ p75s.append(None)
+ elif metric_name == "cumulative_layout_shift":
+ try:
+ p75s.append(float(str(val)))
+ except (ValueError, TypeError):
+ p75s.append(None)
+ else:
+ try:
+ p75s.append(int(val))
+ except (ValueError, TypeError):
+ try:
+ p75s.append(float(val))
+ except (ValueError, TypeError):
+ p75s.append(None)
+
+ # Distributions timeseries
+ histogram_ts = metric_data.get("histogramTimeseries", [])
+ good_pcts = []
+ if len(histogram_ts) >= 3:
+ good_densities = histogram_ts[0].get("densities", [])
+ for d in good_densities:
+ if d is None or str(d) == "NaN":
+ good_pcts.append(None)
+ else:
+ try:
+ good_pcts.append(round(float(d) * 100, 1))
+ except (ValueError, TypeError):
+ good_pcts.append(None)
+
+ # Extract needs_improvement (bin 1) and poor (bin 2) percentages
+ ni_pcts = []
+ poor_pcts = []
+ if len(histogram_ts) >= 3:
+ for bin_idx, target_list in [(1, ni_pcts), (2, poor_pcts)]:
+ bin_densities = histogram_ts[bin_idx].get("densities", [])
+ for d in bin_densities:
+ if d is None or str(d) == "NaN":
+ target_list.append(None)
+ else:
+ try:
+ target_list.append(round(float(d) * 100, 1))
+ except (ValueError, TypeError):
+ target_list.append(None)
+
+ result["metrics"][metric_name] = {
+ "label": thresholds["label"],
+ "unit": thresholds["unit"],
+ "p75_values": p75s,
+ "good_percentages": good_pcts,
+ "needs_improvement_percentages": ni_pcts,
+ "poor_percentages": poor_pcts,
+ "latest_p75": p75s[-1] if p75s and p75s[-1] is not None else None,
+ "good_threshold": thresholds["good"],
+ "poor_threshold": thresholds["poor"],
+ }
+
+ # Trend analysis
+ result["trends"] = detect_trends(result["metrics"])
+
+ return result
+
+
+def detect_trends(metrics: dict) -> dict:
+ """
+ Analyze p75 timeseries to detect trends.
+
+ Compares the average of the last 4 weeks to the average of the first 4 weeks.
+
+ Returns:
+ Dictionary mapping metric names to trend info:
+ direction (improving/stable/degrading), change_pct, latest, earliest.
+ """
+ trends = {}
+
+ for metric_name, data in metrics.items():
+ p75s = data.get("p75_values", [])
+ valid = [v for v in p75s if v is not None]
+
+ if len(valid) < 8:
+ trends[metric_name] = {
+ "direction": "insufficient_data",
+ "label": data.get("label", metric_name),
+ }
+ continue
+
+ # First 4 valid vs last 4 valid
+ first_4 = valid[:4]
+ last_4 = valid[-4:]
+ avg_first = sum(first_4) / len(first_4)
+ avg_last = sum(last_4) / len(last_4)
+
+ if avg_first == 0:
+ change_pct = 0
+ else:
+ change_pct = ((avg_last - avg_first) / avg_first) * 100
+
+ # For CWV, lower is better (except CLS where lower is also better)
+ # So a negative change_pct means improvement
+ if abs(change_pct) < 5:
+ direction = "stable"
+ elif change_pct < 0:
+ direction = "improving"
+ else:
+ direction = "degrading"
+
+ trends[metric_name] = {
+ "direction": direction,
+ "change_pct": round(change_pct, 1),
+ "earliest_avg": round(avg_first, 3) if data.get("unit") == "" else round(avg_first),
+ "latest_avg": round(avg_last, 3) if data.get("unit") == "" else round(avg_last),
+ "label": data.get("label", metric_name),
+ "data_points": len(valid),
+ }
+
+ return trends
+
+
+def main():
+ parser = argparse.ArgumentParser(
+ description="CrUX History API - Core Web Vitals trends over time"
+ )
+ parser.add_argument("url", help="URL or origin to analyze")
+ parser.add_argument(
+ "--form-factor",
+ choices=["PHONE", "DESKTOP", "TABLET"],
+ help="Filter by form factor",
+ )
+ parser.add_argument(
+ "--api-key",
+ help="Google API key (overrides config/env)",
+ )
+ parser.add_argument(
+ "--origin",
+ action="store_true",
+ help="Force origin-level query (strip path/query)",
+ )
+ parser.add_argument(
+ "--json", "-j",
+ action="store_true",
+ help="Output as JSON",
+ )
+
+ args = parser.parse_args()
+
+ api_key = args.api_key or get_api_key()
+ if not api_key:
+ print("Error: API key required. Use --api-key or configure GOOGLE_API_KEY.", file=sys.stderr)
+ sys.exit(1)
+
+ target = args.url
+ if args.origin:
+ parsed = urlparse(target)
+ target = f"{parsed.scheme}://{parsed.netloc}"
+
+ result = query_history(target, api_key, form_factor=args.form_factor)
+
+ if args.json:
+ print(json.dumps(result, indent=2))
+ else:
+ if result.get("error"):
+ print(f"Error: {result['error']}", file=sys.stderr)
+ sys.exit(1)
+
+ print(f"=== CrUX History ({result.get('form_factor', 'ALL')}) ===")
+ print(f"Target: {result.get('target')}")
+
+ periods = result.get("collection_periods", [])
+ if periods:
+ print(f"Range: {periods[0]['first']} to {periods[-1]['last']} ({len(periods)} weeks)")
+
+ print("\nTrend Analysis:")
+ for name, trend in result.get("trends", {}).items():
+ label = trend.get("label", name)
+ direction = trend.get("direction", "?")
+ if direction == "insufficient_data":
+ print(f" {label}: Insufficient data")
+ continue
+
+ arrow = {"improving": "IMPROVING", "stable": "STABLE", "degrading": "DEGRADING"}.get(direction, "?")
+ change = trend.get("change_pct", 0)
+ earliest = trend.get("earliest_avg")
+ latest = trend.get("latest_avg")
+ print(f" {label}: {arrow} ({change:+.1f}%) | {earliest} -> {latest}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/scripts/ga4_report.py b/scripts/ga4_report.py
new file mode 100644
index 0000000..9de2d93
--- /dev/null
+++ b/scripts/ga4_report.py
@@ -0,0 +1,478 @@
+#!/usr/bin/env python3
+"""
+GA4 Data API v1beta - organic traffic reporting.
+
+Queries the Google Analytics Data API for organic search traffic,
+top landing pages, and session metrics with channel filtering.
+
+Usage:
+ python ga4_report.py --property 123456789
+ python ga4_report.py --property 123456789 --days 90 --report top-pages
+ python ga4_report.py --property 123456789 --report organic --json
+"""
+
+import argparse
+import json
+import sys
+from datetime import datetime, timedelta
+from typing import Optional
+
+try:
+ from google.analytics.data_v1beta import BetaAnalyticsDataClient
+ from google.analytics.data_v1beta.types import (
+ DateRange,
+ Dimension,
+ Filter,
+ FilterExpression,
+ Metric,
+ OrderBy,
+ RunReportRequest,
+ )
+except ImportError:
+ print(
+ "Error: google-analytics-data required. "
+ "Install with: pip install google-analytics-data",
+ file=sys.stderr,
+ )
+ sys.exit(1)
+
+try:
+ from google_auth import get_oauth_credentials, load_config
+except ImportError:
+ import os
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+ from google_auth import get_oauth_credentials, load_config
+
+GA4_SCOPES = ["https://www.googleapis.com/auth/analytics.readonly"]
+
+
+def _build_ga4_client():
+ """Build the GA4 BetaAnalyticsDataClient."""
+ credentials = get_oauth_credentials(GA4_SCOPES)
+ if not credentials:
+ return None
+ try:
+ return BetaAnalyticsDataClient(credentials=credentials)
+ except Exception as e:
+ print(f"Error building GA4 client: {e}", file=sys.stderr)
+ return None
+
+
+def _resolve_property(property_id: str) -> str:
+ """Ensure property ID is in the correct format."""
+ if not property_id:
+ return ""
+ if property_id.startswith("properties/"):
+ return property_id
+ return f"properties/{property_id}"
+
+
+def organic_traffic_report(
+ property_id: str,
+ days: int = 28,
+ limit: int = 100,
+) -> dict:
+ """
+ Generate organic traffic report from GA4.
+
+ Filters by sessionDefaultChannelGroup == "Organic Search" and returns
+ daily sessions, top landing pages, and key metrics.
+
+ Args:
+ property_id: GA4 property ID (numeric or 'properties/123456789').
+ days: Number of days to query (default: 28).
+ limit: Max rows (default: 100).
+
+ Returns:
+ Dictionary with daily_data, top_pages, totals, and quota usage.
+ """
+ result = {
+ "property": property_id,
+ "report": "organic_traffic",
+ "date_range": None,
+ "totals": {},
+ "daily_data": [],
+ "top_pages": [],
+ "quota_tokens_used": None,
+ "error": None,
+ }
+
+ client = _build_ga4_client()
+ if not client:
+ result["error"] = (
+ "Could not build GA4 client. Ensure the service account has "
+ "Viewer access in GA4 Admin > Property Access Management."
+ )
+ return result
+
+ prop = _resolve_property(property_id)
+ start_date = (datetime.now() - timedelta(days=days)).strftime("%Y-%m-%d")
+ end_date = (datetime.now() - timedelta(days=1)).strftime("%Y-%m-%d")
+ result["date_range"] = {"start": start_date, "end": end_date}
+
+ # Daily organic sessions
+ try:
+ daily_request = RunReportRequest(
+ property=prop,
+ dimensions=[Dimension(name="date")],
+ metrics=[
+ Metric(name="sessions"),
+ Metric(name="totalUsers"),
+ Metric(name="screenPageViews"),
+ Metric(name="bounceRate"),
+ Metric(name="averageSessionDuration"),
+ Metric(name="engagementRate"),
+ ],
+ date_ranges=[DateRange(start_date=start_date, end_date=end_date)],
+ dimension_filter=FilterExpression(
+ filter=Filter(
+ field_name="sessionDefaultChannelGroup",
+ string_filter=Filter.StringFilter(
+ match_type=Filter.StringFilter.MatchType.EXACT,
+ value="Organic Search",
+ ),
+ )
+ ),
+ order_bys=[OrderBy(dimension=OrderBy.DimensionOrderBy(dimension_name="date"))],
+ limit=days + 5,
+ return_property_quota=True,
+ )
+
+ daily_response = client.run_report(daily_request)
+
+ for row in daily_response.rows:
+ result["daily_data"].append({
+ "date": row.dimension_values[0].value,
+ "sessions": int(row.metric_values[0].value),
+ "users": int(row.metric_values[1].value),
+ "pageviews": int(row.metric_values[2].value),
+ "bounce_rate": round(float(row.metric_values[3].value) * 100, 1),
+ "avg_session_duration": round(float(row.metric_values[4].value), 1),
+ "engagement_rate": round(float(row.metric_values[5].value) * 100, 1),
+ })
+
+ # Quota info
+ if daily_response.property_quota:
+ pq = daily_response.property_quota
+ result["quota_tokens_used"] = {
+ "daily_consumed": pq.tokens_per_day.consumed if pq.tokens_per_day else None,
+ "daily_remaining": pq.tokens_per_day.remaining if pq.tokens_per_day else None,
+ "hourly_consumed": pq.tokens_per_hour.consumed if pq.tokens_per_hour else None,
+ "hourly_remaining": pq.tokens_per_hour.remaining if pq.tokens_per_hour else None,
+ }
+
+ except Exception as e:
+ error_str = str(e)
+ if "403" in error_str or "PERMISSION_DENIED" in error_str:
+ result["error"] = (
+ f"Permission denied for property '{property_id}'. "
+ "Add the service account email as Viewer in "
+ "GA4 Admin > Property Access Management."
+ )
+ elif "404" in error_str or "NOT_FOUND" in error_str:
+ result["error"] = (
+ f"Property '{property_id}' not found. "
+ "Verify the numeric property ID in GA4 Admin > Property Details."
+ )
+ else:
+ result["error"] = f"GA4 API error: {e}"
+ return result
+
+ # Top landing pages by organic sessions
+ try:
+ pages_request = RunReportRequest(
+ property=prop,
+ dimensions=[Dimension(name="landingPage")],
+ metrics=[
+ Metric(name="sessions"),
+ Metric(name="totalUsers"),
+ Metric(name="screenPageViews"),
+ Metric(name="bounceRate"),
+ Metric(name="engagementRate"),
+ ],
+ date_ranges=[DateRange(start_date=start_date, end_date=end_date)],
+ dimension_filter=FilterExpression(
+ filter=Filter(
+ field_name="sessionDefaultChannelGroup",
+ string_filter=Filter.StringFilter(
+ match_type=Filter.StringFilter.MatchType.EXACT,
+ value="Organic Search",
+ ),
+ )
+ ),
+ order_bys=[
+ OrderBy(
+ metric=OrderBy.MetricOrderBy(metric_name="sessions"),
+ desc=True,
+ )
+ ],
+ limit=limit,
+ )
+
+ pages_response = client.run_report(pages_request)
+
+ for row in pages_response.rows:
+ result["top_pages"].append({
+ "landing_page": row.dimension_values[0].value,
+ "sessions": int(row.metric_values[0].value),
+ "users": int(row.metric_values[1].value),
+ "pageviews": int(row.metric_values[2].value),
+ "bounce_rate": round(float(row.metric_values[3].value) * 100, 1),
+ "engagement_rate": round(float(row.metric_values[4].value) * 100, 1),
+ })
+
+ except Exception as e:
+ # Non-fatal: daily data succeeded, pages failed
+ result["pages_error"] = f"Error fetching top pages: {e}"
+
+ # Calculate totals
+ if result["daily_data"]:
+ total_sessions = sum(d["sessions"] for d in result["daily_data"])
+ total_users = sum(d["users"] for d in result["daily_data"])
+ total_pageviews = sum(d["pageviews"] for d in result["daily_data"])
+ result["totals"] = {
+ "sessions": total_sessions,
+ "users": total_users,
+ "pageviews": total_pageviews,
+ "avg_daily_sessions": round(total_sessions / len(result["daily_data"]), 1),
+ }
+
+ return result
+
+
+def top_pages_report(
+ property_id: str,
+ days: int = 28,
+ limit: int = 50,
+) -> dict:
+ """
+ Get top organic landing pages from GA4.
+
+ Args:
+ property_id: GA4 property ID.
+ days: Number of days.
+ limit: Max pages to return.
+
+ Returns:
+ Dictionary with top pages ranked by organic sessions.
+ """
+ report = organic_traffic_report(property_id, days, limit)
+ # Slim it down to just pages
+ return {
+ "property": property_id,
+ "report": "top_organic_pages",
+ "date_range": report.get("date_range"),
+ "pages": report.get("top_pages", []),
+ "total_organic_sessions": report.get("totals", {}).get("sessions", 0),
+ "quota_tokens_used": report.get("quota_tokens_used"),
+ "error": report.get("error"),
+ }
+
+
+def device_breakdown(
+ property_id: str,
+ days: int = 28,
+) -> dict:
+ """
+ Organic sessions broken down by device category.
+
+ Args:
+ property_id: GA4 property ID.
+ days: Number of days.
+
+ Returns:
+ Dictionary with device breakdown data.
+ """
+ result = {"property": property_id, "report": "device_breakdown", "devices": [], "error": None}
+
+ client = _build_ga4_client()
+ if not client:
+ result["error"] = "Could not build GA4 client."
+ return result
+
+ prop = _resolve_property(property_id)
+ start_date = (datetime.now() - timedelta(days=days)).strftime("%Y-%m-%d")
+ end_date = (datetime.now() - timedelta(days=1)).strftime("%Y-%m-%d")
+ result["date_range"] = {"start": start_date, "end": end_date}
+
+ try:
+ request = RunReportRequest(
+ property=prop,
+ dimensions=[Dimension(name="deviceCategory")],
+ metrics=[
+ Metric(name="sessions"),
+ Metric(name="totalUsers"),
+ Metric(name="bounceRate"),
+ Metric(name="engagementRate"),
+ ],
+ date_ranges=[DateRange(start_date=start_date, end_date=end_date)],
+ dimension_filter=FilterExpression(
+ filter=Filter(
+ field_name="sessionDefaultChannelGroup",
+ string_filter=Filter.StringFilter(
+ match_type=Filter.StringFilter.MatchType.EXACT,
+ value="Organic Search",
+ ),
+ )
+ ),
+ order_bys=[OrderBy(metric=OrderBy.MetricOrderBy(metric_name="sessions"), desc=True)],
+ )
+ response = client.run_report(request)
+ for row in response.rows:
+ result["devices"].append({
+ "category": row.dimension_values[0].value,
+ "sessions": int(row.metric_values[0].value),
+ "users": int(row.metric_values[1].value),
+ "bounce_rate": round(float(row.metric_values[2].value) * 100, 1),
+ "engagement_rate": round(float(row.metric_values[3].value) * 100, 1),
+ })
+ except Exception as e:
+ result["error"] = f"GA4 device breakdown error: {e}"
+
+ return result
+
+
+def country_breakdown(
+ property_id: str,
+ days: int = 28,
+ limit: int = 20,
+) -> dict:
+ """
+ Organic sessions broken down by country.
+
+ Args:
+ property_id: GA4 property ID.
+ days: Number of days.
+ limit: Max countries to return.
+
+ Returns:
+ Dictionary with country breakdown data.
+ """
+ result = {"property": property_id, "report": "country_breakdown", "countries": [], "error": None}
+
+ client = _build_ga4_client()
+ if not client:
+ result["error"] = "Could not build GA4 client."
+ return result
+
+ prop = _resolve_property(property_id)
+ start_date = (datetime.now() - timedelta(days=days)).strftime("%Y-%m-%d")
+ end_date = (datetime.now() - timedelta(days=1)).strftime("%Y-%m-%d")
+ result["date_range"] = {"start": start_date, "end": end_date}
+
+ try:
+ request = RunReportRequest(
+ property=prop,
+ dimensions=[Dimension(name="country")],
+ metrics=[
+ Metric(name="sessions"),
+ Metric(name="totalUsers"),
+ ],
+ date_ranges=[DateRange(start_date=start_date, end_date=end_date)],
+ dimension_filter=FilterExpression(
+ filter=Filter(
+ field_name="sessionDefaultChannelGroup",
+ string_filter=Filter.StringFilter(
+ match_type=Filter.StringFilter.MatchType.EXACT,
+ value="Organic Search",
+ ),
+ )
+ ),
+ order_bys=[OrderBy(metric=OrderBy.MetricOrderBy(metric_name="sessions"), desc=True)],
+ limit=limit,
+ )
+ response = client.run_report(request)
+ for row in response.rows:
+ result["countries"].append({
+ "country": row.dimension_values[0].value,
+ "sessions": int(row.metric_values[0].value),
+ "users": int(row.metric_values[1].value),
+ })
+ except Exception as e:
+ result["error"] = f"GA4 country breakdown error: {e}"
+
+ return result
+
+
+def main():
+ parser = argparse.ArgumentParser(
+ description="GA4 Data API - organic traffic reporting"
+ )
+ parser.add_argument(
+ "--property", "-p",
+ help="GA4 property ID (numeric, e.g., 123456789). Uses config default if not specified.",
+ )
+ parser.add_argument("--days", "-d", type=int, default=28, help="Number of days (default: 28)")
+ parser.add_argument(
+ "--report", "-r",
+ choices=["organic", "top-pages", "device", "country"],
+ default="organic",
+ help="Report type (default: organic)",
+ )
+ parser.add_argument("--limit", type=int, default=50, help="Max rows (default: 50)")
+ parser.add_argument("--json", "-j", action="store_true", help="Output as JSON")
+
+ args = parser.parse_args()
+
+ # Resolve property
+ prop = args.property
+ if not prop:
+ config = load_config()
+ prop = config.get("ga4_property_id") or ""
+ # Strip 'properties/' prefix if present for consistency
+ if prop and prop.startswith("properties/"):
+ prop = prop[len("properties/"):]
+ if not prop:
+ print(
+ "Error: No GA4 property specified. Use --property or set ga4_property_id in config.",
+ file=sys.stderr,
+ )
+ sys.exit(1)
+
+ if args.report == "top-pages":
+ result = top_pages_report(prop, args.days, args.limit)
+ elif args.report == "device":
+ result = device_breakdown(prop, args.days)
+ elif args.report == "country":
+ result = country_breakdown(prop, args.days, args.limit)
+ else:
+ result = organic_traffic_report(prop, args.days, args.limit)
+
+ if result.get("error"):
+ print(f"Error: {result['error']}", file=sys.stderr)
+ if not args.json:
+ sys.exit(1)
+
+ if args.json:
+ print(json.dumps(result, indent=2, default=str))
+ else:
+ if args.report == "top-pages":
+ print(f"=== Top Organic Landing Pages ===")
+ print(f"Property: {prop} | Period: {result.get('date_range', {}).get('start')} to {result.get('date_range', {}).get('end')}")
+ print(f"Total organic sessions: {result.get('total_organic_sessions', 0):,}")
+ print()
+ for i, page in enumerate(result.get("pages", [])[:20], 1):
+ print(f" {i:2d}. {page['landing_page']}")
+ print(f" Sessions: {page['sessions']:,} | Users: {page['users']:,} | Bounce: {page['bounce_rate']}%")
+ else:
+ totals = result.get("totals", {})
+ print(f"=== GA4 Organic Traffic Report ===")
+ print(f"Property: {prop}")
+ dr = result.get("date_range", {})
+ print(f"Period: {dr.get('start')} to {dr.get('end')}")
+ print(f"\nSessions: {totals.get('sessions', 0):,} | Users: {totals.get('users', 0):,} | Pageviews: {totals.get('pageviews', 0):,}")
+ print(f"Avg Daily Sessions: {totals.get('avg_daily_sessions', 0):,.0f}")
+
+ quota = result.get("quota_tokens_used")
+ if quota and quota.get("daily_remaining") is not None:
+ print(f"\nQuota: {quota['daily_consumed']} tokens used / {quota['daily_remaining']} remaining (daily)")
+
+ pages = result.get("top_pages", [])
+ if pages:
+ print(f"\nTop {min(10, len(pages))} Organic Landing Pages:")
+ for i, page in enumerate(pages[:10], 1):
+ print(f" {i:2d}. {page['landing_page']} ({page['sessions']:,} sessions)")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/scripts/google_auth.py b/scripts/google_auth.py
new file mode 100644
index 0000000..e460cac
--- /dev/null
+++ b/scripts/google_auth.py
@@ -0,0 +1,795 @@
+#!/usr/bin/env python3
+"""
+Google API credential management for Claude SEO.
+
+Loads and validates credentials for Google Search Console, PageSpeed Insights,
+CrUX, Indexing API, and GA4. Supports service accounts, OAuth web credentials
+with token refresh, API keys, and environment variable fallbacks.
+
+Usage:
+ python google_auth.py --check # Check all credentials
+ python google_auth.py --check gsc # Check specific service
+ python google_auth.py --check --json # JSON output
+ python google_auth.py --setup # Show setup instructions
+ python google_auth.py --tier # Show detected credential tier
+ python google_auth.py --auth --creds /path/to/client_secret.json # OAuth browser flow
+"""
+
+import argparse
+import json
+import os
+import sys
+import time
+from typing import Optional
+
+CONFIG_PATH = os.path.expanduser("~/.config/claude-seo/google-api.json")
+TOKEN_PATH = os.path.expanduser("~/.config/claude-seo/oauth-token.json")
+
+# Service-to-scope mapping
+SCOPES = {
+ "gsc_readonly": "https://www.googleapis.com/auth/webmasters.readonly",
+ "gsc_write": "https://www.googleapis.com/auth/webmasters",
+ "indexing": "https://www.googleapis.com/auth/indexing",
+ "ga4": "https://www.googleapis.com/auth/analytics.readonly",
+}
+
+# Which services need which auth type
+SERVICE_AUTH = {
+ "psi": "api_key",
+ "crux": "api_key",
+ "crux_history": "api_key",
+ "gsc": "oauth_or_sa",
+ "indexing": "oauth_or_sa",
+ "ga4": "oauth_or_sa",
+}
+
+OAUTH_SCOPES = (
+ "https://www.googleapis.com/auth/indexing "
+ "https://www.googleapis.com/auth/webmasters "
+ "https://www.googleapis.com/auth/analytics.readonly"
+)
+OAUTH_REDIRECT_URI = "http://localhost:8085"
+
+# Human-readable service names
+SERVICE_NAMES = {
+ "psi": "PageSpeed Insights v5",
+ "crux": "Chrome UX Report (CrUX) API",
+ "crux_history": "CrUX History API",
+ "gsc": "Google Search Console API",
+ "indexing": "Google Indexing API v3",
+ "ga4": "GA4 Data API v1beta",
+}
+
+
+def load_config() -> dict:
+ """
+ Load configuration from config file with environment variable fallbacks.
+
+ Reads ~/.config/claude-seo/google-api.json first. Any missing fields
+ are filled from environment variables.
+
+ Returns:
+ Dictionary with keys: service_account_path, api_key,
+ default_property, ga4_property_id. Missing values are None.
+ """
+ config = {
+ "service_account_path": None,
+ "api_key": None,
+ "default_property": None,
+ "ga4_property_id": None,
+ }
+
+ # Load from config file
+ if os.path.exists(CONFIG_PATH):
+ try:
+ with open(CONFIG_PATH, "r") as f:
+ file_config = json.load(f)
+ config.update({k: v for k, v in file_config.items() if v})
+ except (json.JSONDecodeError, IOError) as e:
+ print(f"Warning: Could not read config file: {e}", file=sys.stderr)
+
+ # Environment variable fallbacks
+ if not config["service_account_path"]:
+ config["service_account_path"] = os.environ.get("GOOGLE_APPLICATION_CREDENTIALS")
+
+ if not config["api_key"]:
+ config["api_key"] = os.environ.get("GOOGLE_API_KEY")
+
+ if not config["ga4_property_id"]:
+ config["ga4_property_id"] = os.environ.get("GA4_PROPERTY_ID")
+
+ if not config["default_property"]:
+ config["default_property"] = os.environ.get("GSC_PROPERTY")
+
+ return config
+
+
+def get_service_account_credentials(scopes: list):
+ """
+ Load Google service account credentials.
+
+ Args:
+ scopes: List of OAuth scope URLs.
+
+ Returns:
+ google.oauth2.service_account.Credentials object, or None on failure.
+ """
+ try:
+ from google.oauth2 import service_account
+ except ImportError:
+ print(
+ "Error: google-auth library required. "
+ "Install with: pip install google-auth",
+ file=sys.stderr,
+ )
+ return None
+
+ config = load_config()
+ sa_path = config.get("service_account_path")
+
+ if not sa_path:
+ return None
+
+ sa_path = os.path.expanduser(sa_path)
+ if not os.path.exists(sa_path):
+ print(
+ f"Error: Service account file not found: {sa_path}",
+ file=sys.stderr,
+ )
+ return None
+
+ try:
+ credentials = service_account.Credentials.from_service_account_file(
+ sa_path, scopes=scopes
+ )
+ return credentials
+ except Exception as e:
+ print(f"Error loading service account: {e}", file=sys.stderr)
+ return None
+
+
+def _load_oauth_client(creds_path: str) -> Optional[dict]:
+ """Load OAuth client credentials from a client_secret JSON file."""
+ try:
+ with open(creds_path, "r") as f:
+ data = json.load(f)
+ return data.get("web", data.get("installed", {}))
+ except (json.JSONDecodeError, IOError) as e:
+ print(f"Error reading OAuth client file: {e}", file=sys.stderr)
+ return None
+
+
+def _load_oauth_token() -> Optional[dict]:
+ """Load saved OAuth token from TOKEN_PATH."""
+ if not os.path.exists(TOKEN_PATH):
+ return None
+ try:
+ with open(TOKEN_PATH, "r") as f:
+ return json.load(f)
+ except (json.JSONDecodeError, IOError):
+ return None
+
+
+def _save_oauth_token(token_data: dict):
+ """Save OAuth token to TOKEN_PATH."""
+ os.makedirs(os.path.dirname(TOKEN_PATH), exist_ok=True)
+ with open(TOKEN_PATH, "w") as f:
+ json.dump(token_data, f, indent=2)
+
+
+def _refresh_oauth_token(client: dict, token_data: dict) -> Optional[dict]:
+ """Refresh an expired OAuth token using the refresh_token."""
+ import urllib.parse
+ import urllib.request
+
+ if not token_data.get("refresh_token"):
+ return None
+
+ params = urllib.parse.urlencode({
+ "client_id": client["client_id"],
+ "client_secret": client["client_secret"],
+ "refresh_token": token_data["refresh_token"],
+ "grant_type": "refresh_token",
+ }).encode()
+
+ try:
+ req = urllib.request.Request(client.get("token_uri", "https://oauth2.googleapis.com/token"), data=params)
+ with urllib.request.urlopen(req) as resp:
+ new_data = json.loads(resp.read())
+ token_data["access_token"] = new_data["access_token"]
+ token_data["expires_at"] = time.time() + new_data.get("expires_in", 3600)
+ _save_oauth_token(token_data)
+ return token_data
+ except Exception as e:
+ print(f"Error refreshing OAuth token: {e}", file=sys.stderr)
+ return None
+
+
+def get_oauth_credentials(scopes: list):
+ """
+ Get OAuth credentials from saved token, refreshing if needed.
+
+ Falls back to service account if no OAuth token is available.
+
+ Args:
+ scopes: List of OAuth scope URLs (used for service account fallback).
+
+ Returns:
+ google.oauth2.credentials.Credentials or service_account.Credentials, or None.
+ """
+ config = load_config()
+
+ # Try OAuth token first
+ token_data = _load_oauth_token()
+ if token_data and token_data.get("access_token"):
+ # Check if token needs refresh
+ if time.time() > token_data.get("expires_at", 0) - 60:
+ oauth_creds_path = config.get("oauth_client_path")
+ if oauth_creds_path:
+ client = _load_oauth_client(os.path.expanduser(oauth_creds_path))
+ if client:
+ token_data = _refresh_oauth_token(client, token_data)
+ if not token_data:
+ print("OAuth token refresh failed. Re-run --auth.", file=sys.stderr)
+ return get_service_account_credentials(scopes)
+
+ if token_data and token_data.get("access_token"):
+ try:
+ from google.oauth2.credentials import Credentials
+ # Read client_secret from client file, never from stored token
+ client_secret = None
+ oauth_path = config.get("oauth_client_path")
+ if oauth_path:
+ client_data = _load_oauth_client(os.path.expanduser(oauth_path))
+ if client_data:
+ client_secret = client_data.get("client_secret")
+ return Credentials(
+ token=token_data["access_token"],
+ refresh_token=token_data.get("refresh_token"),
+ token_uri="https://oauth2.googleapis.com/token",
+ client_id=token_data.get("client_id"),
+ client_secret=client_secret,
+ )
+ except ImportError:
+ print("Error: google-auth required. Install with: pip install google-auth", file=sys.stderr)
+
+ # Fall back to service account
+ return get_service_account_credentials(scopes)
+
+
+def run_oauth_flow(creds_path: str):
+ """
+ Run OAuth browser-based authentication flow.
+
+ Opens a browser for consent, captures the auth code via local HTTP server,
+ exchanges for tokens, and saves them.
+
+ Args:
+ creds_path: Path to the OAuth client_secret JSON file.
+ """
+ import http.server
+ import urllib.parse
+ import urllib.request
+ import webbrowser
+
+ client = _load_oauth_client(creds_path)
+ if not client:
+ print("Error: Could not load OAuth client credentials.", file=sys.stderr)
+ sys.exit(1)
+
+ auth_url = (
+ f"{client.get('auth_uri', 'https://accounts.google.com/o/oauth2/auth')}"
+ f"?client_id={client['client_id']}"
+ f"&redirect_uri={urllib.parse.quote(OAUTH_REDIRECT_URI)}"
+ f"&response_type=code"
+ f"&scope={urllib.parse.quote(OAUTH_SCOPES)}"
+ f"&access_type=offline&prompt=consent"
+ )
+
+ auth_code = [None]
+
+ class Handler(http.server.BaseHTTPRequestHandler):
+ def do_GET(self):
+ params = urllib.parse.parse_qs(urllib.parse.urlparse(self.path).query)
+ if "code" in params:
+ auth_code[0] = params["code"][0]
+ self.send_response(200)
+ self.send_header("Content-Type", "text/html")
+ self.end_headers()
+ self.wfile.write(b"<h1>Authentication successful!</h1><p>Close this tab.</p>")
+ else:
+ self.send_response(400)
+ self.end_headers()
+ def log_message(self, *a):
+ pass
+
+ server = http.server.HTTPServer(("localhost", 8085), Handler)
+ server.timeout = 300
+
+ print(f"\nOpen this URL in your browser:\n\n{auth_url}\n")
+ print("Waiting up to 5 minutes for authentication...")
+
+ try:
+ webbrowser.open(auth_url)
+ except Exception:
+ pass
+
+ server.handle_request()
+ server.server_close()
+
+ if not auth_code[0]:
+ print("\nAuthentication failed or timed out.", file=sys.stderr)
+ print("If the browser showed 'localhost refused to connect', copy the full URL")
+ print("from the browser address bar and run:")
+ print(f" python scripts/google_auth.py --exchange --creds {creds_path} --code 'THE_CODE'")
+ sys.exit(1)
+
+ # Exchange code for tokens
+ _exchange_code(client, auth_code[0])
+
+
+def _exchange_code(client: dict, code: str):
+ """Exchange an authorization code for tokens."""
+ import urllib.parse
+ import urllib.request
+
+ params = urllib.parse.urlencode({
+ "code": code,
+ "client_id": client["client_id"],
+ "client_secret": client["client_secret"],
+ "redirect_uri": OAUTH_REDIRECT_URI,
+ "grant_type": "authorization_code",
+ }).encode()
+
+ try:
+ req = urllib.request.Request(
+ client.get("token_uri", "https://oauth2.googleapis.com/token"), data=params
+ )
+ with urllib.request.urlopen(req) as resp:
+ token_data = json.loads(resp.read())
+ token_data["expires_at"] = time.time() + token_data.get("expires_in", 3600)
+ token_data["client_id"] = client["client_id"]
+ # SECURITY: Never store client_secret in token file. It stays in client_secret.json only.
+ token_data.pop("client_secret", None)
+ _save_oauth_token(token_data)
+ print("OAuth token saved successfully!")
+
+ # Also save the OAuth client path to config
+ config = load_config()
+ # Don't overwrite existing config, just suggest
+ print(f"\nToken saved to: {TOKEN_PATH}")
+ except Exception as e:
+ print(f"Error exchanging authorization code: {e}", file=sys.stderr)
+ sys.exit(1)
+
+
+def validate_url(url: str) -> bool:
+ """
+ Validate a URL for use with Google APIs. Rejects private/loopback addresses.
+
+ Args:
+ url: URL string to validate.
+
+ Returns:
+ True if the URL is a valid public http/https URL, False otherwise.
+ """
+ from urllib.parse import urlparse
+
+ parsed = urlparse(url)
+ if parsed.scheme not in ("http", "https"):
+ return False
+ if not parsed.hostname:
+ return False
+ blocked = [
+ "localhost", "127.0.0.1", "0.0.0.0", "::1",
+ "metadata.google.internal",
+ ]
+ if parsed.hostname in blocked:
+ return False
+ # Block private IP ranges (10.x, 172.16-31.x, 192.168.x)
+ try:
+ import ipaddress
+ ip = ipaddress.ip_address(parsed.hostname)
+ if ip.is_private or ip.is_loopback or ip.is_link_local:
+ return False
+ except ValueError:
+ pass # Not an IP address (hostname), which is fine
+ return True
+
+
+def get_api_key() -> Optional[str]:
+ """
+ Get the Google API key from config or environment.
+
+ Returns:
+ API key string, or None if not configured.
+ """
+ config = load_config()
+ return config.get("api_key")
+
+
+def build_service(api_name: str, version: str, scopes: list):
+ """
+ Build a Google API discovery service client.
+
+ Args:
+ api_name: API name (e.g., 'searchconsole', 'indexing', 'pagespeedonline').
+ version: API version (e.g., 'v1', 'v3', 'v5').
+ scopes: OAuth scopes needed.
+
+ Returns:
+ googleapiclient.discovery.Resource object, or None on failure.
+ """
+ try:
+ from googleapiclient.discovery import build
+ except ImportError:
+ print(
+ "Error: google-api-python-client required. "
+ "Install with: pip install google-api-python-client",
+ file=sys.stderr,
+ )
+ return None
+
+ credentials = get_oauth_credentials(scopes)
+ if not credentials:
+ return None
+
+ try:
+ service = build(api_name, version, credentials=credentials)
+ return service
+ except Exception as e:
+ print(f"Error building {api_name} service: {e}", file=sys.stderr)
+ return None
+
+
+def check_credentials(service: str) -> dict:
+ """
+ Validate credentials for a specific Google API service.
+
+ Args:
+ service: One of 'psi', 'crux', 'crux_history', 'gsc', 'indexing', 'ga4'.
+
+ Returns:
+ Dictionary with:
+ - available: bool
+ - method: 'api_key' or 'service_account'
+ - service: service name
+ - error: error message or None
+ """
+ result = {
+ "available": False,
+ "method": SERVICE_AUTH.get(service, "unknown"),
+ "service": SERVICE_NAMES.get(service, service),
+ "error": None,
+ }
+
+ config = load_config()
+
+ if SERVICE_AUTH.get(service) == "api_key":
+ api_key = config.get("api_key")
+ if api_key:
+ result["available"] = True
+ else:
+ result["error"] = (
+ "No API key found. Set GOOGLE_API_KEY environment variable "
+ f"or add 'api_key' to {CONFIG_PATH}"
+ )
+
+ elif SERVICE_AUTH.get(service) == "oauth_or_sa":
+ # Check OAuth token first
+ token_data = _load_oauth_token()
+ if token_data and token_data.get("access_token"):
+ result["available"] = True
+ result["method"] = "oauth_token"
+ expired = time.time() > token_data.get("expires_at", 0) - 60
+ if expired and token_data.get("refresh_token"):
+ result["note"] = "Token expired but refresh_token available (will auto-refresh)"
+ elif expired:
+ result["available"] = False
+ result["error"] = "OAuth token expired and no refresh_token. Re-run --auth."
+ else:
+ # Fall back to service account
+ sa_path = config.get("service_account_path")
+ if not sa_path:
+ result["error"] = (
+ "No OAuth token or service account found. Either:\n"
+ " 1. Run: python scripts/google_auth.py --auth --creds /path/to/client_secret.json\n"
+ f" 2. Or add 'service_account_path' to {CONFIG_PATH}"
+ )
+ else:
+ sa_path = os.path.expanduser(sa_path)
+ if not os.path.exists(sa_path):
+ result["error"] = f"Service account file not found: {sa_path}"
+ else:
+ try:
+ with open(sa_path, "r") as f:
+ sa_data = json.load(f)
+ if "client_email" not in sa_data or "private_key" not in sa_data:
+ result["error"] = "Service account JSON missing required fields (client_email, private_key)"
+ else:
+ result["available"] = True
+ result["method"] = "service_account"
+ result["client_email"] = sa_data.get("client_email")
+ except (json.JSONDecodeError, IOError) as e:
+ result["error"] = f"Invalid service account file: {e}"
+
+ # GA4 also needs property ID
+ if service == "ga4" and result["available"]:
+ ga4_id = config.get("ga4_property_id")
+ if not ga4_id:
+ result["available"] = False
+ result["error"] = (
+ "Credentials found but no GA4 property ID configured. "
+ f"Set GA4_PROPERTY_ID or add 'ga4_property_id' to {CONFIG_PATH}"
+ )
+ else:
+ result["error"] = f"Unknown service: {service}"
+
+ return result
+
+
+def detect_tier() -> dict:
+ """
+ Detect the credential tier available.
+
+ Returns:
+ Dictionary with:
+ - tier: 0, 1, or 2
+ - description: human-readable tier description
+ - capabilities: list of available API groups
+ - missing: what's needed for the next tier
+ """
+ config = load_config()
+
+ has_api_key = bool(config.get("api_key"))
+ has_authenticated = False
+ has_ga4 = False
+ auth_method = None
+
+ # Check OAuth token
+ token_data = _load_oauth_token()
+ if token_data and token_data.get("access_token"):
+ has_authenticated = True
+ auth_method = "oauth_token"
+
+ # Check service account
+ if not has_authenticated:
+ sa_path = config.get("service_account_path")
+ if sa_path:
+ sa_path = os.path.expanduser(sa_path)
+ if os.path.exists(sa_path):
+ try:
+ with open(sa_path, "r") as f:
+ sa_data = json.load(f)
+ if "client_email" in sa_data and "private_key" in sa_data:
+ has_authenticated = True
+ auth_method = "service_account"
+ except (json.JSONDecodeError, IOError):
+ pass
+
+ if has_authenticated and config.get("ga4_property_id"):
+ has_ga4 = True
+
+ if has_ga4:
+ return {
+ "tier": 2,
+ "description": "Full (API key + Service Account + GA4)",
+ "capabilities": [
+ "PageSpeed Insights", "CrUX", "CrUX History",
+ "Search Console", "URL Inspection", "Sitemaps",
+ "Indexing API", "GA4 Organic Traffic",
+ ],
+ "missing": None,
+ }
+ elif has_authenticated:
+ return {
+ "tier": 1,
+ "description": "Authenticated (API key + OAuth/Service Account)",
+ "capabilities": [
+ "PageSpeed Insights", "CrUX", "CrUX History",
+ "Search Console", "URL Inspection", "Sitemaps",
+ "Indexing API",
+ ],
+ "missing": "Add 'ga4_property_id' to unlock GA4 organic traffic reports",
+ }
+ elif has_api_key:
+ return {
+ "tier": 0,
+ "description": "API Key Only",
+ "capabilities": [
+ "PageSpeed Insights", "CrUX", "CrUX History",
+ ],
+ "missing": "Add a service account to unlock Search Console, URL Inspection, and Indexing API",
+ }
+ else:
+ return {
+ "tier": -1,
+ "description": "No credentials configured",
+ "capabilities": [],
+ "missing": (
+ f"Create config at {CONFIG_PATH} with at minimum an 'api_key' field. "
+ "Run with --setup for full instructions."
+ ),
+ }
+
+
+def print_setup_instructions():
+ """Print step-by-step setup instructions."""
+ print("""
+Google SEO API Setup Instructions
+=================================
+
+1. CREATE A GOOGLE CLOUD PROJECT
+ - Go to https://console.cloud.google.com
+ - Create a new project (or select existing)
+ - Note the project ID
+
+2. ENABLE APIs
+ In API Library (APIs & Services > Library), enable:
+ - Google Search Console API
+ - PageSpeed Insights API
+ - Chrome UX Report API
+ - Web Search Indexing API (for Indexing API)
+ - Google Analytics Data API (for GA4)
+
+3. CREATE AN API KEY (for PSI, CrUX -- free, no service account needed)
+ - APIs & Services > Credentials > Create Credentials > API key
+ - Restrict to: PageSpeed Insights API, Chrome UX Report API
+
+4. CREATE A SERVICE ACCOUNT (for GSC, Indexing API, GA4)
+ - IAM & Admin > Service Accounts > Create Service Account
+ - Download JSON key file, store securely
+
+5. GRANT ACCESS
+ - Search Console: Settings > Users and permissions > Add user
+ Paste the service account client_email, set as Owner (for Indexing API) or Full (read-only)
+ - GA4: Admin > Property Access Management > Add
+ Paste email, set Viewer role
+
+6. CREATE CONFIG FILE
+ mkdir -p ~/.config/claude-seo
+ Save to ~/.config/claude-seo/google-api.json:
+
+ {
+ "service_account_path": "/path/to/service_account.json",
+ "api_key": "AIzaSy...",
+ "default_property": "sc-domain:example.com",
+ "ga4_property_id": "properties/123456789"
+ }
+
+7. VERIFY
+ python scripts/google_auth.py --check
+
+ENVIRONMENT VARIABLE ALTERNATIVES:
+ GOOGLE_API_KEY - API key
+ GOOGLE_APPLICATION_CREDENTIALS - Path to service account JSON
+ GA4_PROPERTY_ID - GA4 property ID (e.g., properties/123456789)
+ GSC_PROPERTY - Default Search Console property
+""")
+
+
+def main():
+ parser = argparse.ArgumentParser(
+ description="Google API credential management for Claude SEO"
+ )
+ parser.add_argument(
+ "--check",
+ nargs="?",
+ const="all",
+ metavar="SERVICE",
+ help="Check credentials. Optionally specify service: psi, crux, gsc, indexing, ga4",
+ )
+ parser.add_argument(
+ "--setup",
+ action="store_true",
+ help="Show setup instructions",
+ )
+ parser.add_argument(
+ "--tier",
+ action="store_true",
+ help="Show detected credential tier",
+ )
+ parser.add_argument(
+ "--json",
+ action="store_true",
+ help="Output as JSON",
+ )
+ parser.add_argument(
+ "--auth",
+ action="store_true",
+ help="Run OAuth browser-based authentication flow",
+ )
+ parser.add_argument(
+ "--exchange",
+ action="store_true",
+ help="Manually exchange an auth code for tokens",
+ )
+ parser.add_argument(
+ "--creds",
+ help="Path to OAuth client_secret JSON file (for --auth and --exchange)",
+ )
+ parser.add_argument(
+ "--code",
+ help="Authorization code to exchange (for --exchange)",
+ )
+
+ args = parser.parse_args()
+
+ if args.auth:
+ if not args.creds:
+ print("Error: --creds is required with --auth", file=sys.stderr)
+ sys.exit(1)
+ run_oauth_flow(args.creds)
+ return
+
+ if args.exchange:
+ if not args.creds or not args.code:
+ print("Error: --creds and --code are required with --exchange", file=sys.stderr)
+ sys.exit(1)
+ client = _load_oauth_client(args.creds)
+ if client:
+ _exchange_code(client, args.code)
+ return
+
+ if args.setup:
+ print_setup_instructions()
+ return
+
+ if args.tier:
+ tier_info = detect_tier()
+ if args.json:
+ print(json.dumps(tier_info, indent=2))
+ else:
+ print(f"Credential Tier: {tier_info['tier']} -- {tier_info['description']}")
+ if tier_info["capabilities"]:
+ print(f"Available APIs: {', '.join(tier_info['capabilities'])}")
+ if tier_info["missing"]:
+ print(f"Next tier: {tier_info['missing']}")
+ return
+
+ if args.check:
+ services = (
+ list(SERVICE_AUTH.keys())
+ if args.check == "all"
+ else [args.check]
+ )
+
+ results = {}
+ for svc in services:
+ if svc not in SERVICE_AUTH:
+ results[svc] = {"available": False, "error": f"Unknown service: {svc}"}
+ continue
+ results[svc] = check_credentials(svc)
+
+ if args.json:
+ tier_info = detect_tier()
+ output = {"tier": tier_info, "services": results}
+ print(json.dumps(output, indent=2))
+ else:
+ tier_info = detect_tier()
+ print(f"Credential Tier: {tier_info['tier']} -- {tier_info['description']}")
+ print()
+ for svc, result in results.items():
+ status = "OK" if result["available"] else "MISSING"
+ print(f" [{status}] {result.get('service', svc)}")
+ if result.get("error"):
+ print(f" {result['error']}")
+ if result.get("client_email"):
+ print(f" Service account: {result['client_email']}")
+ print()
+ if tier_info["missing"]:
+ print(f"Tip: {tier_info['missing']}")
+ return
+
+ # Default: show tier
+ tier_info = detect_tier()
+ if args.json:
+ print(json.dumps(tier_info, indent=2))
+ else:
+ print(f"Credential Tier: {tier_info['tier']} -- {tier_info['description']}")
+ if tier_info["missing"]:
+ print(f"Run --setup for configuration instructions.")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/scripts/google_report.py b/scripts/google_report.py
new file mode 100644
index 0000000..1d9b5b3
--- /dev/null
+++ b/scripts/google_report.py
@@ -0,0 +1,2273 @@
+#!/usr/bin/env python3
+"""
+Google SEO Report Generator - Professional PDF/HTML reports from API data.
+
+Consumes JSON output from seo-google scripts and generates formatted reports
+with charts, analytics, and actionable recommendations.
+
+Usage:
+ python google_report.py --type cwv-audit --data cwv-data.json --domain example.com
+ python google_report.py --type gsc-performance --data gsc-data.json --domain example.com
+ python google_report.py --type indexation --data inspect-data.json --domain example.com
+ python google_report.py --type full --data full-data.json --domain example.com
+ cat data.json | python google_report.py --type cwv-audit --domain example.com
+"""
+
+import argparse
+import json
+import os
+import sys
+from datetime import datetime
+from pathlib import Path
+from typing import Optional
+
+try:
+ import matplotlib
+ matplotlib.use("Agg")
+ import matplotlib.pyplot as plt
+ import matplotlib.patches as mpatches
+ import numpy as np
+except ImportError:
+ print("Error: matplotlib required. Install with: pip install matplotlib", file=sys.stderr)
+ sys.exit(1)
+
+try:
+ from weasyprint import HTML
+except ImportError:
+ print("Error: weasyprint required. Install with: pip install weasyprint", file=sys.stderr)
+ sys.exit(1)
+
+
+# ─── Brand Colors ────────────────────────────────────────────────────────────
+
+BRAND = {
+ "primary": "#1e3a5f", # Navy (headers, borders)
+ "secondary": "#4a5568", # Warm gray
+ "accent": "#b8860b", # Dark gold
+ "success": "#2d6a4f", # Forest green (pass/good)
+ "warning": "#d4740e", # Warm amber (warnings)
+ "danger": "#c53030", # Deep red (fail/critical)
+ "dark": "#1a1a2e", # Dark navy
+ "light_bg": "#faf9f7", # Warm cream
+ "grid": "#d6d3cc", # Warm border
+ "muted": "#6b7280", # Muted text
+}
+
+
+def _score_color(score):
+ """Return brand color based on Lighthouse-style score thresholds."""
+ if score >= 90:
+ return BRAND["success"]
+ elif score >= 50:
+ return BRAND["warning"]
+ return BRAND["danger"]
+
+
+def _rating_color(rating):
+ """Return brand color based on CrUX rating strings."""
+ r = str(rating).lower().replace("-", "_").replace(" ", "_")
+ if r in ("good", "pass", "fast"):
+ return BRAND["success"]
+ elif r in ("needs_improvement", "needs-improvement", "average", "warn"):
+ return BRAND["warning"]
+ return BRAND["danger"]
+
+
+def _score_class(score):
+ """Return CSS class for TOC score badges."""
+ if score >= 80:
+ return "score-good"
+ elif score >= 50:
+ return "score-warn"
+ return "score-bad"
+
+
+def _rating_css_class(rating):
+ """Return CSS status class from a rating string."""
+ r = str(rating).lower()
+ if "good" in r or "pass" in r:
+ return "status-pass"
+ elif "poor" in r or "fail" in r:
+ return "status-fail"
+ return "status-warn"
+
+
+# ─── Chart Setup ─────────────────────────────────────────────────────────────
+
+def _setup_matplotlib():
+ """Configure matplotlib for professional chart output."""
+ plt.rcParams.update({
+ "font.family": "serif",
+ "font.serif": ["DejaVu Serif", "Times New Roman", "Georgia"],
+ "font.size": 11,
+ "axes.titlesize": 14,
+ "axes.titleweight": "bold",
+ "axes.labelsize": 11,
+ "axes.facecolor": "white",
+ "figure.facecolor": "white",
+ "axes.grid": False,
+ "axes.spines.top": False,
+ "axes.spines.right": False,
+ })
+
+
+_setup_matplotlib()
+
+
+# ─── Chart Functions ─────────────────────────────────────────────────────────
+
+def chart_lighthouse_gauges(data: dict, output_dir: Path) -> str:
+ """Generate 2x2 Lighthouse score gauges."""
+ scores = data.get("lighthouse_scores", {})
+ if not scores:
+ return ""
+
+ fig, axes = plt.subplots(2, 2, figsize=(8, 4), subplot_kw={"projection": "polar"})
+ categories = [
+ ("performance", "Performance"),
+ ("accessibility", "Accessibility"),
+ ("best-practices", "Best Practices"),
+ ("seo", "SEO"),
+ ]
+
+ for ax, (key, label) in zip(axes.flat, categories):
+ score = scores.get(key, 0)
+ theta_bg = np.linspace(np.pi, 0, 100)
+ theta_fill = np.linspace(np.pi, np.pi - (score / 100) * np.pi, 100)
+
+ ax.plot(theta_bg, [1] * 100, linewidth=14, color="#e2e8f0", solid_capstyle="round")
+ ax.plot(theta_fill, [1] * 100, linewidth=14, color=_score_color(score), solid_capstyle="round")
+
+ ax.text(np.pi / 2, 0.35, f"{score}", ha="center", va="center",
+ fontsize=24, fontweight="bold", color=BRAND["dark"])
+ ax.text(np.pi / 2, -0.05, label, ha="center", va="center",
+ fontsize=10, color=BRAND["muted"])
+
+ ax.set_ylim(0, 1.3)
+ ax.set_rticks([])
+ ax.set_thetagrids([])
+ ax.spines["polar"].set_visible(False)
+
+ plt.tight_layout(pad=2)
+ path = output_dir / "lighthouse_gauges.png"
+ plt.savefig(path, dpi=200, bbox_inches="tight", facecolor="white")
+ plt.close()
+ return str(path)
+
+
+def chart_cwv_distributions(data: dict, output_dir: Path) -> str:
+ """Generate stacked horizontal bars for CWV metric distributions."""
+ crux = data.get("crux", {})
+ metrics = crux.get("metrics", {})
+ if not metrics:
+ return ""
+
+ cwv_order = [
+ "largest_contentful_paint", "interaction_to_next_paint",
+ "cumulative_layout_shift", "first_contentful_paint",
+ "experimental_time_to_first_byte",
+ ]
+
+ labels, goods, nis, poors = [], [], [], []
+ for name in cwv_order:
+ m = metrics.get(name)
+ if not m or "distribution" not in m:
+ continue
+ d = m["distribution"]
+ labels.append(m.get("label", name))
+ goods.append(d.get("good", 0))
+ nis.append(d.get("needs_improvement", 0))
+ poors.append(d.get("poor", 0))
+
+ if not labels:
+ return ""
+
+ fig, ax = plt.subplots(figsize=(8, max(2.5, len(labels) * 0.7)))
+ y = range(len(labels))
+
+ ax.barh(y, goods, color=BRAND["success"], label="Good", height=0.5)
+ ax.barh(y, nis, left=goods, color=BRAND["warning"], label="Needs Improvement", height=0.5)
+ left2 = [g + n for g, n in zip(goods, nis)]
+ ax.barh(y, poors, left=left2, color=BRAND["danger"], label="Poor", height=0.5)
+
+ ax.set_yticks(y)
+ ax.set_yticklabels(labels)
+ ax.set_xlim(0, 100)
+ ax.set_xlabel("% of page loads")
+ ax.legend(loc="lower right", fontsize=9)
+ ax.invert_yaxis()
+
+ for i, (g, n, p) in enumerate(zip(goods, nis, poors)):
+ if g > 10:
+ ax.text(g / 2, i, f"{g:.0f}%", ha="center", va="center",
+ fontsize=8, color="white", fontweight="bold")
+ if n > 10:
+ ax.text(g + n / 2, i, f"{n:.0f}%", ha="center", va="center",
+ fontsize=8, color="white", fontweight="bold")
+ if p > 10:
+ ax.text(g + n + p / 2, i, f"{p:.0f}%", ha="center", va="center",
+ fontsize=8, color="white", fontweight="bold")
+
+ plt.tight_layout()
+ path = output_dir / "cwv_distributions.png"
+ plt.savefig(path, dpi=200, bbox_inches="tight", facecolor="white")
+ plt.close()
+ return str(path)
+
+
+def chart_cwv_timeline(data: dict, output_dir: Path) -> str:
+ """Generate CWV timeline chart from CrUX History data."""
+ metrics = data.get("metrics", {})
+ periods = data.get("collection_periods", [])
+ if not metrics or not periods:
+ return ""
+
+ cwv_metrics = [
+ "largest_contentful_paint",
+ "interaction_to_next_paint",
+ "cumulative_layout_shift",
+ ]
+ available = [m for m in cwv_metrics if m in metrics]
+ if not available:
+ return ""
+
+ fig, axes = plt.subplots(len(available), 1, figsize=(10, 3 * len(available)), sharex=True)
+ if len(available) == 1:
+ axes = [axes]
+
+ x_labels = [p.get("last", "")[-5:] for p in periods] # MM-DD format
+ x = range(len(x_labels))
+
+ for ax, metric_name in zip(axes, available):
+ m = metrics[metric_name]
+ p75s = m.get("p75_values", [])
+ label = m.get("label", metric_name)
+ good_t = m.get("good_threshold", 0)
+ poor_t = m.get("poor_threshold", 0)
+
+ valid_x = [i for i, v in enumerate(p75s) if v is not None]
+ valid_y = [v for v in p75s if v is not None]
+
+ if not valid_y:
+ continue
+
+ # Threshold bands
+ if good_t and poor_t:
+ ax.axhspan(0, good_t, alpha=0.1, color=BRAND["success"])
+ ax.axhspan(good_t, poor_t, alpha=0.1, color=BRAND["warning"])
+ ax.axhline(y=good_t, color=BRAND["success"], linestyle="--", alpha=0.5, linewidth=1)
+ ax.axhline(y=poor_t, color=BRAND["danger"], linestyle="--", alpha=0.5, linewidth=1)
+
+ ax.plot(valid_x, valid_y, color=BRAND["primary"], linewidth=2, marker="o", markersize=3)
+ ax.fill_between(valid_x, valid_y, alpha=0.1, color=BRAND["primary"])
+
+ unit = m.get("unit", "")
+ ax.set_ylabel(f"{label} (p75{unit})")
+ ax.set_title(label, fontsize=12, fontweight="bold")
+
+ if x_labels:
+ step = max(1, len(x_labels) // 8)
+ axes[-1].set_xticks(range(0, len(x_labels), step))
+ axes[-1].set_xticklabels(
+ [x_labels[i] for i in range(0, len(x_labels), step)],
+ rotation=45, fontsize=8,
+ )
+
+ plt.tight_layout()
+ path = output_dir / "cwv_timeline.png"
+ plt.savefig(path, dpi=200, bbox_inches="tight", facecolor="white")
+ plt.close()
+ return str(path)
+
+
+def chart_top_queries(data: dict, output_dir: Path) -> str:
+ """Generate horizontal bar chart of top queries by impressions."""
+ rows = data.get("rows", [])
+ if not rows:
+ return ""
+
+ # Sort by impressions (more meaningful than clicks for new sites)
+ top = sorted(rows, key=lambda r: r.get("impressions", 0), reverse=True)[:12]
+ top = [r for r in top if r.get("impressions", 0) > 0]
+ if not top:
+ return ""
+
+ labels = [r.get("query", r.get("keys", ["?"])[0])[:35] for r in top]
+ impressions = [r.get("impressions", 0) for r in top]
+ clicks = [r.get("clicks", 0) for r in top]
+
+ if not impressions or max(impressions) < 3:
+ return ""
+
+ fig, ax = plt.subplots(figsize=(7, max(2, len(labels) * 0.3)))
+ y = range(len(labels))
+ bars = ax.barh(y, impressions, color=BRAND["primary"], height=0.55, label="Impressions")
+ if any(c > 0 for c in clicks):
+ ax.barh(y, clicks, color=BRAND["success"], height=0.55, label="Clicks")
+ ax.legend(fontsize=8, loc="lower right")
+ ax.set_yticks(y)
+ ax.set_yticklabels(labels, fontsize=8)
+ ax.set_xlabel("Count")
+ ax.invert_yaxis()
+
+ for bar, val in zip(bars, clicks):
+ if val > 0:
+ ax.text(
+ bar.get_width() + max(clicks) * 0.02,
+ bar.get_y() + bar.get_height() / 2,
+ str(val), va="center", fontsize=8, color=BRAND["dark"],
+ )
+
+ plt.tight_layout()
+ path = output_dir / "top_queries.png"
+ plt.savefig(path, dpi=200, bbox_inches="tight", facecolor="white")
+ plt.close()
+ return str(path)
+
+
+def chart_index_status(data: dict, output_dir: Path) -> str:
+ """Generate donut chart for URL inspection results."""
+ summary = data.get("summary", {})
+ if not summary:
+ return ""
+
+ labels, sizes, colors = [], [], []
+ for key, label, color in [
+ ("pass", "Indexed", BRAND["success"]),
+ ("fail", "Not Indexed", BRAND["danger"]),
+ ("neutral", "Neutral", BRAND["grid"]),
+ ("error", "Error", BRAND["muted"]),
+ ]:
+ val = summary.get(key, 0)
+ if val > 0:
+ labels.append(f"{label} ({val})")
+ sizes.append(val)
+ colors.append(color)
+
+ if not sizes:
+ return ""
+
+ fig, ax = plt.subplots(figsize=(4.5, 3.5))
+ wedges, texts, autotexts = ax.pie(
+ sizes, labels=labels, colors=colors, autopct="%1.0f%%",
+ startangle=90, pctdistance=0.75, textprops={"fontsize": 9},
+ )
+ centre = plt.Circle((0, 0), 0.50, fc="white")
+ ax.add_artist(centre)
+ total = sum(sizes)
+ ax.text(0, 0, f"{total}\nURLs", ha="center", va="center",
+ fontsize=16, fontweight="bold", color=BRAND["dark"])
+
+ plt.tight_layout()
+ path = output_dir / "index_status.png"
+ plt.savefig(path, dpi=200, bbox_inches="tight", facecolor="white")
+ plt.close()
+ return str(path)
+
+
+# ─── CSS Template ────────────────────────────────────────────────────────────
+
+def _build_css(domain: str) -> str:
+ """
+ Professional A4 report CSS adapted from generate_pdf.py.
+
+ Uses Times New Roman / DejaVu Serif body font. All proven layout classes
+ from the dexdia.com audit report are preserved with the WeasyPrint-safe
+ patterns (div.section for page-break, float:right for badges,
+ display:table for two-column layouts).
+ """
+ return f"""\
+ @page {{
+ size: A4;
+ margin: 22mm 18mm 25mm 18mm;
+ @bottom-center {{
+ content: "Page " counter(page) " of " counter(pages);
+ font-size: 9pt;
+ color: #6b7280;
+ font-family: 'DejaVu Serif', 'Times New Roman', Georgia, serif;
+ }}
+ @bottom-left {{
+ content: "Confidential";
+ font-size: 7pt;
+ color: #d6d3cc;
+ font-family: 'DejaVu Serif', 'Times New Roman', Georgia, serif;
+ }}
+ @bottom-right {{
+ content: "{domain} Google SEO Report";
+ font-size: 8pt;
+ color: #cbd5e1;
+ font-family: 'DejaVu Serif', 'Times New Roman', Georgia, serif;
+ }}
+ }}
+
+ @page :first {{
+ margin: 0;
+ @bottom-left {{ content: none; }}
+ @bottom-center {{ content: none; }}
+ @bottom-right {{ content: none; }}
+ }}
+
+ @page toc {{
+ @bottom-center {{
+ content: counter(page);
+ font-size: 9pt;
+ color: #6b7280;
+ }}
+ }}
+
+ * {{
+ box-sizing: border-box;
+ margin: 0;
+ padding: 0;
+ }}
+
+ body {{
+ font-family: 'Times New Roman', 'DejaVu Serif', Georgia, serif;
+ font-size: 10pt;
+ line-height: 1.55;
+ color: #1e293b;
+ background: white;
+ }}
+
+ /* ─── Title Page (Clean White) ─── */
+ .title-page {{
+ page: first;
+ width: 210mm;
+ height: 297mm;
+ background: #ffffff;
+ display: flex;
+ flex-direction: column;
+ justify-content: center;
+ align-items: center;
+ text-align: center;
+ color: #1a1a2e;
+ position: relative;
+ padding: 50mm 30mm 40mm 30mm;
+ border-top: 6mm solid #1e3a5f;
+ }}
+
+ .title-page .badge {{
+ background: #f7f6f3;
+ border: 1px solid #d6d3cc;
+ border-radius: 20px;
+ padding: 6px 18px;
+ font-size: 9pt;
+ letter-spacing: 2px;
+ text-transform: uppercase;
+ margin-bottom: 15mm;
+ color: #1e3a5f;
+ }}
+
+ .title-page h1 {{
+ font-size: 28pt;
+ font-weight: bold;
+ margin-bottom: 5mm;
+ letter-spacing: -0.5px;
+ line-height: 1.2;
+ color: #1a1a2e;
+ }}
+
+ .title-page .subtitle {{
+ font-size: 13pt;
+ color: #6b7280;
+ margin-bottom: 12mm;
+ font-weight: 300;
+ }}
+
+ .title-page .url {{
+ font-size: 12pt;
+ color: #1e3a5f;
+ margin-bottom: 15mm;
+ padding: 4mm 8mm;
+ border: 1px solid #d6d3cc;
+ border-radius: 6px;
+ background: #faf9f7;
+ }}
+
+ .title-page .score-box {{
+ background: #faf9f7;
+ border: 2px solid #d6d3cc;
+ border-radius: 12px;
+ padding: 6mm 12mm;
+ margin-bottom: 15mm;
+ }}
+
+ .title-page .score-number {{
+ font-size: 42pt;
+ font-weight: bold;
+ color: #1e3a5f;
+ line-height: 1;
+ }}
+
+ .title-page .score-label {{
+ font-size: 10pt;
+ color: #6b7280;
+ margin-top: 2mm;
+ }}
+
+ .title-page .meta {{
+ font-size: 9pt;
+ color: #6b7280;
+ margin-top: 8mm;
+ padding-top: 5mm;
+ border-top: 1px solid #d6d3cc;
+ }}
+
+ .title-page .meta span {{
+ margin: 0 8px;
+ }}
+
+ /* ─── Table of Contents ─── */
+ .toc-page {{
+ page: toc;
+ page-break-before: always;
+ }}
+
+ .toc-page h2 {{
+ font-size: 18pt;
+ color: #1e3a5f;
+ margin-bottom: 8mm;
+ padding-bottom: 3mm;
+ border-bottom: 2px solid #1e3a5f;
+ }}
+
+ .toc-list {{
+ list-style: none;
+ padding: 0;
+ }}
+
+ .toc-list li {{
+ padding: 2mm 0;
+ border-bottom: 1px solid #f1f5f9;
+ overflow: hidden;
+ }}
+
+ .toc-list li.toc-section {{
+ font-weight: bold;
+ font-size: 11pt;
+ padding-top: 4mm;
+ color: #0f172a;
+ }}
+
+ .toc-list li.toc-sub {{
+ padding-left: 8mm;
+ font-size: 9.5pt;
+ color: #475569;
+ }}
+
+ .toc-score {{
+ display: inline-block;
+ float: right;
+ padding: 1px 8px;
+ border-radius: 10px;
+ font-size: 9pt;
+ font-weight: bold;
+ color: white;
+ }}
+
+ .score-good {{ background: #2d6a4f; }}
+ .score-warn {{ background: #d4740e; }}
+ .score-bad {{ background: #c53030; }}
+
+ /* ─── Section Styles ─── */
+ div.section {{
+ page-break-before: always;
+ }}
+
+ .section-header {{
+ background: #faf9f7;
+ border-left: 4px solid #1e3a5f;
+ padding: 5mm 6mm;
+ margin-bottom: 6mm;
+ page-break-after: avoid;
+ }}
+
+ .section-header h2 {{
+ font-size: 16pt;
+ color: #0f172a;
+ margin-bottom: 1mm;
+ }}
+
+ .section-header .section-score {{
+ font-size: 12pt;
+ font-weight: bold;
+ float: right;
+ margin-top: -6mm;
+ }}
+
+ h3 {{
+ font-size: 12pt;
+ color: #1e3a5f;
+ margin-top: 6mm;
+ margin-bottom: 3mm;
+ padding-bottom: 1.5mm;
+ border-bottom: 1px solid #d6d3cc;
+ page-break-after: avoid;
+ }}
+
+ h4 {{
+ font-size: 10.5pt;
+ color: #334155;
+ margin-top: 4mm;
+ margin-bottom: 2mm;
+ page-break-after: avoid;
+ }}
+
+ p {{
+ margin-bottom: 3mm;
+ color: #334155;
+ }}
+
+ .highlight {{
+ background: #fef3c7;
+ border-left: 3px solid #d4740e;
+ padding: 3mm 4mm;
+ margin: 4mm 0;
+ font-size: 9.5pt;
+ /* allow page breaks to prevent white gaps */
+ }}
+
+ .critical-box {{
+ background: #fef2f2;
+ border-left: 3px solid #c53030;
+ padding: 3mm 4mm;
+ margin: 4mm 0;
+ font-size: 9.5pt;
+ /* allow page breaks to prevent white gaps */
+ }}
+
+ .success-box {{
+ background: #f0fdf4;
+ border-left: 3px solid #2d6a4f;
+ padding: 3mm 4mm;
+ margin: 4mm 0;
+ font-size: 9.5pt;
+ /* allow page breaks to prevent white gaps */
+ }}
+
+ /* ─── Tables ─── */
+ table {{
+ width: 100%;
+ border-collapse: collapse;
+ margin: 4mm 0 6mm 0;
+ font-size: 9pt;
+ }}
+
+ thead th {{
+ background: #f7f6f3;
+ color: #0f172a;
+ font-weight: bold;
+ padding: 3mm 4mm;
+ text-align: left;
+ border-bottom: 2px solid #d6d3cc;
+ font-size: 9pt;
+ }}
+
+ tbody td {{
+ padding: 2.5mm 3mm;
+ border-bottom: 1px solid #f1f5f9;
+ vertical-align: top;
+ }}
+
+ tbody tr:nth-child(even) {{
+ background: #fdfcfa;
+ }}
+
+ .status-pass {{
+ color: #2d6a4f;
+ font-weight: bold;
+ }}
+
+ .status-fail {{
+ color: #c53030;
+ font-weight: bold;
+ }}
+
+ .status-warn {{
+ color: #d4740e;
+ font-weight: bold;
+ }}
+
+ .status-partial {{
+ color: #4a5568;
+ font-weight: bold;
+ }}
+
+ /* ─── Charts ─── */
+ .chart-container {{
+ text-align: center;
+ margin: 4mm 0;
+ }}
+
+ .chart-container img {{
+ max-width: 100%;
+ max-height: 120mm;
+ height: auto;
+ }}
+
+ .chart-caption {{
+ font-size: 8.5pt;
+ color: #6b7280;
+ font-style: italic;
+ margin-top: 2mm;
+ text-align: center;
+ }}
+
+ .chart-half {{
+ display: inline-block;
+ width: 48%;
+ vertical-align: top;
+ text-align: center;
+ margin: 2mm 0;
+ }}
+
+ .chart-half img {{
+ max-width: 100%;
+ height: auto;
+ }}
+
+ /* ─── Two column layout ─── */
+ .two-col {{
+ display: table;
+ width: 100%;
+ table-layout: fixed;
+ margin: 3mm 0;
+ }}
+
+ .two-col .col {{
+ display: table-cell;
+ vertical-align: top;
+ padding: 0 2mm;
+ }}
+
+ .four-col {{
+ display: table;
+ width: 100%;
+ table-layout: fixed;
+ margin: 3mm 0;
+ }}
+
+ .four-col .col {{
+ display: table-cell;
+ vertical-align: top;
+ padding: 0 1.5mm;
+ }}
+
+ /* ─── Metric Cards ─── */
+ .metric-card {{
+ background: #faf9f7;
+ border: 1px solid #d6d3cc;
+ border-radius: 6px;
+ padding: 2.5mm 3mm;
+ text-align: center;
+ margin: 2mm 0;
+ }}
+
+ .metric-card .value {{
+ font-size: 14pt;
+ font-weight: bold;
+ line-height: 1.2;
+ }}
+
+ .metric-card .label {{
+ font-size: 7.5pt;
+ color: #64748b;
+ text-transform: uppercase;
+ letter-spacing: 0.5px;
+ margin-top: 1mm;
+ }}
+
+ /* ─── Action Plan ─── */
+ .action-item {{
+ background: #faf9f7;
+ border-radius: 4px;
+ padding: 3mm 4mm;
+ margin: 3mm 0;
+ border-left: 3px solid #cbd5e1;
+ /* allow page breaks to prevent white gaps */
+ }}
+
+ .action-item.critical {{
+ border-left-color: #c53030;
+ background: #fdf2f2;
+ }}
+
+ .action-item.high {{
+ border-left-color: #d4740e;
+ background: #fdf8ef;
+ }}
+
+ .action-item.medium {{
+ border-left-color: #1e3a5f;
+ background: #f0f4f8;
+ }}
+
+ .action-item.low {{
+ border-left-color: #94a3b8;
+ }}
+
+ .action-item h4 {{
+ margin-top: 0;
+ margin-bottom: 1.5mm;
+ border-bottom: none;
+ padding-bottom: 0;
+ }}
+
+ .action-item .effort {{
+ font-size: 8.5pt;
+ color: #64748b;
+ float: right;
+ }}
+
+ .priority-tag {{
+ display: inline-block;
+ padding: 0.5mm 3mm;
+ border-radius: 3px;
+ font-size: 8pt;
+ font-weight: bold;
+ color: white;
+ margin-right: 2mm;
+ vertical-align: middle;
+ }}
+
+ .priority-critical {{ background: #c53030; }}
+ .priority-high {{ background: #d4740e; }}
+ .priority-medium {{ background: #1e3a5f; }}
+ .priority-low {{ background: #94a3b8; }}
+
+ /* ─── Code blocks ─── */
+ .code-block {{
+ background: #1e293b;
+ color: #e2e8f0;
+ padding: 3mm 4mm;
+ border-radius: 4px;
+ font-family: 'DejaVu Sans Mono', monospace;
+ font-size: 8pt;
+ line-height: 1.6;
+ margin: 3mm 0;
+ white-space: pre-wrap;
+ word-break: break-all;
+ /* allow page breaks to prevent white gaps */
+ }}
+
+ /* ─── Divider ─── */
+ .divider {{
+ border: none;
+ border-top: 1px solid #d6d3cc;
+ margin: 5mm 0;
+ }}
+
+ /* ─── Roadmap ─── */
+ .roadmap-phase {{
+ background: #faf9f7;
+ border-radius: 6px;
+ padding: 4mm 5mm;
+ margin: 4mm 0;
+ border: 1px solid #d6d3cc;
+ /* allow page breaks to prevent white gaps */
+ }}
+
+ .roadmap-phase h4 {{
+ margin-top: 0;
+ border-bottom: none;
+ color: #1e3a5f;
+ }}
+
+ .roadmap-phase ul {{
+ margin: 2mm 0 0 5mm;
+ padding: 0;
+ }}
+
+ .roadmap-phase li {{
+ margin-bottom: 1.5mm;
+ font-size: 9.5pt;
+ color: #334155;
+ }}
+
+ /* ─── Lists ─── */
+ ul {{
+ margin-left: 5mm;
+ margin-bottom: 3mm;
+ }}
+
+ li {{
+ margin-bottom: 1.5mm;
+ }}
+
+ /* ─── Data freshness ─── */
+ .data-freshness {{
+ font-size: 8pt;
+ color: #6b7280;
+ font-style: italic;
+ margin-top: 4mm;
+ padding-top: 2mm;
+ border-top: 1px solid #d6d3cc;
+ }}
+"""
+
+
+# ─── HTML Helpers ────────────────────────────────────────────────────────────
+
+def _img_tag(path, alt="Chart"):
+ """Convert file path to file:// URI img tag for WeasyPrint."""
+ if not path:
+ return ""
+ return f'<img src="file://{path}" style="max-width: 100%;" alt="{alt}">'
+
+
+def _chart_html(path, caption, fig_num, alt="Chart"):
+ """Build a complete chart container with figure caption."""
+ if not path:
+ return ""
+ return (
+ f' <div class="chart-container">\n'
+ f' <img src="file://{path}" style="width: 85%;" alt="{alt}">\n'
+ f' <div class="chart-caption">Figure {fig_num}: {caption}</div>\n'
+ f' </div>\n'
+ )
+
+
+def _metric_card(value, label, color=None):
+ """Build a metric card HTML block."""
+ style = f' style="color: {color};"' if color else ""
+ return (
+ f' <div class="metric-card">\n'
+ f' <div class="value"{style}>{value}</div>\n'
+ f' <div class="label">{label}</div>\n'
+ f' </div>\n'
+ )
+
+
+# ─── Section Builders ────────────────────────────────────────────────────────
+
+def _build_title_page(domain, report_title, subtitle, score=None, score_label=None, meta_items=None):
+ """Build the gradient title page."""
+ score_html = ""
+ if score is not None:
+ score_html = (
+ f' <div class="score-box">\n'
+ f' <div class="score-number">{score}'
+ f'<span style="font-size: 20pt; color: #94a3b8;">/100</span></div>\n'
+ f' <div class="score-label">{score_label or "Lighthouse Performance Score"}</div>\n'
+ f' </div>\n'
+ )
+
+ meta_html = ""
+ if meta_items:
+ spans = "\n ".join(f"<span>{item}</span>" for item in meta_items)
+ meta_html = (
+ f' <div class="meta">\n'
+ f' {spans}\n'
+ f' </div>\n'
+ )
+
+ # Google logo (if available in charts dir)
+ google_logo_path = Path(__file__).parent.parent / "charts" / "google_logo.png"
+ google_logo_html = ""
+ if google_logo_path.exists():
+ google_logo_html = (
+ f' <div style="margin-top: 8mm;">\n'
+ f' <img src="file://{google_logo_path}" style="height: 20px; opacity: 0.7;" alt="Google">\n'
+ f' <div style="font-size: 7pt; color: #6b7280; margin-top: 2mm;">Powered by Google APIs</div>\n'
+ f' </div>\n'
+ )
+
+ return (
+ f'\n<!-- {"=" * 55} TITLE PAGE {"=" * 3} -->\n'
+ f'<div class="title-page">\n'
+ f' <div class="badge">{report_title}</div>\n'
+ f' <h1>{domain}</h1>\n'
+ f' <div class="subtitle">Prepared by Claude SEO</div>\n'
+ f'{score_html}'
+ f'{meta_html}'
+ f'{google_logo_html}'
+ f'</div>\n'
+ )
+
+
+def _build_toc(sections_info):
+ """
+ Build a Table of Contents page.
+
+ sections_info: list of dicts with keys 'num', 'title', 'score' (optional),
+ and 'subs' (list of subtitle strings).
+ """
+ items = []
+ for sec in sections_info:
+ score_html = ""
+ if sec.get("score") is not None:
+ cls = _score_class(sec["score"])
+ score_html = f' <span class="toc-score {cls}">{sec["score"]}</span>'
+ items.append(
+ f' <li class="toc-section">'
+ f'<span>{sec["num"]}. {sec["title"]}</span>{score_html}'
+ f'</li>'
+ )
+ for sub in sec.get("subs", []):
+ items.append(f' <li class="toc-sub"><span>{sub}</span></li>')
+
+ items_html = "\n".join(items)
+ return (
+ f'\n<!-- {"=" * 55} TABLE OF CONTENTS {"=" * 3} -->\n'
+ f'<div class="toc-page">\n'
+ f' <h2>Table of Contents</h2>\n'
+ f' <ul class="toc-list">\n'
+ f'{items_html}\n'
+ f' </ul>\n'
+ f'</div>\n'
+ )
+
+
+def _build_executive_summary(domain, timestamp, data, report_type):
+ """Build the Executive Summary section with metric cards, issues, and wins."""
+ lines = []
+ lines.append(f'\n<!-- {"=" * 55} 1. EXECUTIVE SUMMARY {"=" * 3} -->')
+ lines.append('<div class="section">')
+ lines.append(' <div class="section-header">')
+ lines.append(' <h2>1. Executive Summary</h2>')
+ lines.append(' </div>')
+ lines.append('')
+
+ # Context paragraph
+ lines.append(f' <p>This report presents a comprehensive Google SEO analysis of '
+ f'<strong>{domain}</strong>, generated on {timestamp}. '
+ f'Data was collected from Google PageSpeed Insights, Chrome User Experience '
+ f'Report (CrUX), Google Search Console, and the URL Inspection API as available.</p>')
+ lines.append('')
+
+ # Metric cards row
+ cards = []
+
+ # PSI performance score
+ psi = data.get("psi", {})
+ mobile = psi.get("psi", {}).get("mobile", psi) if isinstance(psi, dict) else {}
+ perf_score = mobile.get("lighthouse_scores", {}).get("performance")
+ if perf_score is not None:
+ color = _score_color(perf_score)
+ cards.append(("perf", f"{perf_score}/100", "Lighthouse Performance", color))
+
+ seo_score = mobile.get("lighthouse_scores", {}).get("seo")
+ if seo_score is not None:
+ color = _score_color(seo_score)
+ cards.append(("seo", f"{seo_score}/100", "Lighthouse SEO", color))
+
+ # GSC totals
+ gsc = data.get("gsc", {})
+ if gsc.get("totals"):
+ clicks = gsc["totals"].get("clicks", 0)
+ cards.append(("clicks", f"{clicks:,}", "Total Clicks", BRAND["primary"]))
+ impr = gsc["totals"].get("impressions", 0)
+ cards.append(("impr", f"{impr:,}", "Impressions", BRAND["secondary"]))
+
+ # Indexation
+ inspection = data.get("inspection", {})
+ if inspection.get("summary"):
+ indexed = inspection["summary"].get("pass", 0)
+ total = inspection.get("total", 0)
+ cards.append(("idx", f"{indexed}/{total}", "Indexed URLs", BRAND["success"]))
+
+ # Render metric cards in a compact row
+ if cards:
+ col_class = "four-col" if len(cards) >= 4 else "two-col"
+ display_cards = cards[:5]
+ lines.append(f' <div class="{col_class}">')
+ for _, val, lbl, clr in display_cards:
+ lines.append(f' <div class="col">')
+ lines.append(_metric_card(val, lbl, clr))
+ lines.append(f' </div>')
+ lines.append(' </div>')
+ lines.append('')
+
+ # Critical issues box
+ issues = []
+ failed_audits = mobile.get("failed_audits", [])
+ if failed_audits:
+ top_fail = sorted(failed_audits, key=lambda a: a.get("score", 1))[:3]
+ for a in top_fail:
+ issues.append(f'<strong>{a.get("title", "Unknown")}</strong> '
+ f'(score: {a.get("score", 0):.0%})')
+
+ seo_audits = mobile.get("seo_audits", [])
+ seo_failed = [a for a in seo_audits if not a.get("pass")]
+ for a in seo_failed[:2]:
+ issues.append(f'<strong>SEO:</strong> {a.get("title", "Unknown")}')
+
+ inspect_fails = inspection.get("summary", {}).get("fail", 0)
+ if inspect_fails:
+ issues.append(f'<strong>{inspect_fails} URL(s)</strong> not indexed')
+
+ if issues:
+ issue_items = "\n".join(f" <li>{i}</li>" for i in issues[:5])
+ lines.append(' <div class="critical-box">')
+ lines.append(' <strong>Critical Issues Found:</strong>')
+ lines.append(' <ol>')
+ lines.append(issue_items)
+ lines.append(' </ol>')
+ lines.append(' </div>')
+ lines.append('')
+
+ # Quick wins box
+ wins = []
+ qw = gsc.get("quick_wins", [])
+ if qw:
+ wins.append(f'{len(qw)} search queries at positions 4-10 with high impressions '
+ f'(small ranking bump = significant traffic)')
+
+ opps = mobile.get("opportunities", [])
+ for o in opps[:3]:
+ savings = o.get("savings_ms", 0)
+ if savings:
+ wins.append(f'{o.get("title", "Optimization")}: save ~{savings}ms')
+
+ if wins:
+ win_items = "\n".join(f" <li>{w}</li>" for w in wins[:5])
+ lines.append(' <div class="success-box">')
+ lines.append(' <strong>Quick Wins:</strong>')
+ lines.append(' <ol>')
+ lines.append(win_items)
+ lines.append(' </ol>')
+ lines.append(' </div>')
+ lines.append('')
+
+ lines.append('</div>')
+ return "\n".join(lines)
+
+
+def _build_cwv_section(psi_data, crux_data, chart_paths, history_data=None, section_num=2):
+ """Build the Core Web Vitals audit section."""
+ fig_counter = [1] # mutable counter for figure numbering
+
+ def next_fig():
+ n = fig_counter[0]
+ fig_counter[0] += 1
+ return n
+
+ lines = []
+ lines.append(f'\n<!-- {"=" * 55} {section_num}. CORE WEB VITALS {"=" * 3} -->')
+ lines.append('<div class="section">')
+ lines.append(' <div class="section-header">')
+ lines.append(f' <h2>{section_num}. Core Web Vitals &amp; Performance</h2>')
+
+ # Section score from Lighthouse performance
+ psi = psi_data if isinstance(psi_data, dict) else {}
+ mobile = psi.get("psi", {}).get("mobile", psi)
+ scores = mobile.get("lighthouse_scores", {})
+ perf = scores.get("performance")
+ if perf is not None:
+ color = _score_color(perf)
+ lines.append(f' <div class="section-score" style="color: {color};">{perf}/100</div>')
+
+ lines.append(' </div>')
+ lines.append('')
+
+ # 2.1 Lighthouse Scores gauges
+ if scores:
+ lines.append(f' <h3>{section_num}.1 Lighthouse Scores</h3>')
+ lines.append('')
+ gauges_path = chart_paths.get("gauges_path", "")
+ lines.append(_chart_html(
+ gauges_path,
+ "Lighthouse audit scores across Performance, Accessibility, Best Practices, and SEO.",
+ next_fig(),
+ "Lighthouse gauge scores",
+ ))
+
+ # Scores summary table
+ lines.append(' <table>')
+ lines.append(' <thead>')
+ lines.append(' <tr><th>Category</th><th>Score</th><th>Rating</th></tr>')
+ lines.append(' </thead>')
+ lines.append(' <tbody>')
+ for key, label in [("performance", "Performance"), ("accessibility", "Accessibility"),
+ ("best-practices", "Best Practices"), ("seo", "SEO")]:
+ s = scores.get(key)
+ if s is not None:
+ cls = "status-pass" if s >= 90 else ("status-warn" if s >= 50 else "status-fail")
+ rating = "Good" if s >= 90 else ("Needs Work" if s >= 50 else "Poor")
+ lines.append(f' <tr><td>{label}</td><td class="{cls}">{s}</td><td>{rating}</td></tr>')
+ lines.append(' </tbody>')
+ lines.append(' </table>')
+ lines.append('')
+
+ # Divider between Lighthouse Scores and Lab Metrics
+ lines.append(' <hr class="divider">')
+
+ # 2.2 Lab Metrics
+ lab = mobile.get("lab_metrics", {})
+ if lab:
+ lines.append(f' <h3>{section_num}.2 Lab Metrics (Simulated)</h3>')
+ lines.append(' <table>')
+ lines.append(' <thead>')
+ lines.append(' <tr><th>Metric</th><th>Value</th><th>Score</th><th>Threshold</th></tr>')
+ lines.append(' </thead>')
+ lines.append(' <tbody>')
+ metric_labels = {
+ "first-contentful-paint": "First Contentful Paint (FCP)",
+ "largest-contentful-paint": "Largest Contentful Paint (LCP)",
+ "total-blocking-time": "Total Blocking Time (TBT)",
+ "cumulative-layout-shift": "Cumulative Layout Shift (CLS)",
+ "speed-index": "Speed Index",
+ "interactive": "Time to Interactive (TTI)",
+ }
+ thresholds = {
+ "first-contentful-paint": "\u2264 1.8s",
+ "largest-contentful-paint": "\u2264 2.5s",
+ "total-blocking-time": "\u2264 200ms",
+ "cumulative-layout-shift": "\u2264 0.1",
+ "speed-index": "\u2264 3.4s",
+ "interactive": "\u2264 3.8s",
+ }
+ for k, v in lab.items():
+ score_val = v.get("score")
+ score_pct = f"{score_val:.0%}" if score_val is not None else "N/A"
+ cls = ("status-pass" if score_val and score_val >= 0.9
+ else ("status-warn" if score_val and score_val >= 0.5 else "status-fail"))
+ label = metric_labels.get(k, k.replace("-", " ").title())
+ threshold = thresholds.get(k, "\u2014")
+ lines.append(f' <tr><td>{label}</td><td>{v.get("display", "")}</td>'
+ f'<td class="{cls}">{score_pct}</td><td>{threshold}</td></tr>')
+ lines.append(' </tbody>')
+ lines.append(' </table>')
+ lines.append('')
+
+ # 2.3 CrUX Field Data
+ crux = crux_data if isinstance(crux_data, dict) else {}
+ crux_metrics = crux.get("metrics", {})
+ if crux_metrics:
+ lines.append(f' <h3>{section_num}.3 CrUX Field Data (28-day Rolling Average)</h3>')
+ lines.append('')
+
+ # Distribution chart
+ dist_path = chart_paths.get("distributions_path", "")
+ lines.append(_chart_html(
+ dist_path,
+ "Core Web Vitals field data distribution across Good, Needs Improvement, and Poor buckets.",
+ next_fig(),
+ "CWV distribution chart",
+ ))
+
+ lines.append(' <table>')
+ lines.append(' <thead>')
+ lines.append(' <tr><th>Metric</th><th>p75</th><th>Rating</th>'
+ '<th>Good %</th><th>NI %</th><th>Poor %</th></tr>')
+ lines.append(' </thead>')
+ lines.append(' <tbody>')
+ for name, m in crux_metrics.items():
+ rating = m.get("rating", "?")
+ dist = m.get("distribution", {})
+ unit = m.get("unit", "")
+ p75 = m.get("p75", "?")
+ display_val = f"{p75:.3f}" if name == "cumulative_layout_shift" else f"{p75}{unit}"
+ cls = _rating_css_class(rating)
+ lines.append(f' <tr><td>{m.get("label", name)}</td><td>{display_val}</td>')
+ lines.append(f' <td class="{cls}">{rating.upper()}</td>')
+ lines.append(f' <td>{dist.get("good", "N/A")}%</td>'
+ f'<td>{dist.get("needs_improvement", "N/A")}%</td>'
+ f'<td>{dist.get("poor", "N/A")}%</td></tr>')
+ lines.append(' </tbody>')
+ lines.append(' </table>')
+
+ cp = crux.get("collection_period", {})
+ if cp:
+ lines.append(f' <p class="data-freshness">Collection period: {cp.get("first", "?")} '
+ f'to {cp.get("last", "?")}. CrUX data is a 28-day rolling average '
+ f'updated daily ~04:00 UTC.</p>')
+ lines.append('')
+ elif crux.get("error"):
+ lines.append(f' <h3>{section_num}.3 CrUX Field Data</h3>')
+ lines.append(f' <div class="highlight"><strong>CrUX Field Data:</strong> '
+ f'{crux["error"]}</div>')
+ lines.append('')
+
+ # CrUX History timeline
+ if history_data and not history_data.get("error"):
+ lines.append(f' <h3>{section_num}.4 Core Web Vitals Trends (25-week)</h3>')
+ timeline_path = chart_paths.get("timeline_path", "")
+ lines.append(_chart_html(
+ timeline_path,
+ "CrUX p75 values over 25 weeks with Good/Poor threshold bands.",
+ next_fig(),
+ "CWV timeline trends",
+ ))
+
+ trends = history_data.get("trends", {})
+ if trends:
+ lines.append(' <table>')
+ lines.append(' <thead>')
+ lines.append(' <tr><th>Metric</th><th>Direction</th><th>Change</th>'
+ '<th>Earliest Avg</th><th>Latest Avg</th></tr>')
+ lines.append(' </thead>')
+ lines.append(' <tbody>')
+ for name, t in trends.items():
+ direction = t.get("direction", "?")
+ cls = ("status-pass" if direction == "improving"
+ else ("status-fail" if direction == "degrading" else ""))
+ lines.append(f' <tr><td>{t.get("label", name)}</td>'
+ f'<td class="{cls}">{direction.upper()}</td>')
+ lines.append(f' <td>{t.get("change_pct", 0):+.1f}%</td>'
+ f'<td>{t.get("earliest_avg", "?")}</td>'
+ f'<td>{t.get("latest_avg", "?")}</td></tr>')
+ lines.append(' </tbody>')
+ lines.append(' </table>')
+ lines.append('')
+
+ # Failed audits
+ failed = mobile.get("failed_audits", [])
+ if failed:
+ sub = f"{section_num}.5" if history_data and not history_data.get("error") else f"{section_num}.4"
+ lines.append(f' <h3>{sub} Failed / Warning Audits ({len(failed)})</h3>')
+ lines.append(' <table>')
+ lines.append(' <thead>')
+ lines.append(' <tr><th>Audit</th><th>Score</th><th>Details</th></tr>')
+ lines.append(' </thead>')
+ lines.append(' <tbody>')
+ for a in failed[:20]:
+ score_pct = f"{a['score']:.0%}" if a.get("score") is not None else "?"
+ lines.append(f' <tr><td>{a.get("title", "")}</td>'
+ f'<td class="status-fail">{score_pct}</td>'
+ f'<td>{a.get("display", "")}</td></tr>')
+ lines.append(' </tbody>')
+ lines.append(' </table>')
+ lines.append('')
+
+ # SEO audit checks
+ seo_audits = mobile.get("seo_audits", [])
+ if seo_audits:
+ seo_failed = [a for a in seo_audits if not a.get("pass")]
+ if seo_failed:
+ lines.append(f' <h3>SEO Audit Issues ({len(seo_failed)})</h3>')
+ for a in seo_failed:
+ lines.append(f' <div class="action-item critical">')
+ lines.append(f' <h4>{a.get("title", "")}</h4>')
+ lines.append(f' </div>')
+ else:
+ lines.append(f' <div class="success-box"><strong>SEO:</strong> '
+ f'All {len(seo_audits)} Lighthouse SEO checks passed.</div>')
+ lines.append('')
+
+ # Accessibility issues
+ a11y = mobile.get("accessibility_audits", [])
+ if a11y:
+ lines.append(f' <h3>Accessibility Issues ({len(a11y)})</h3>')
+ lines.append(' <table>')
+ lines.append(' <thead>')
+ lines.append(' <tr><th>Issue</th><th>Score</th></tr>')
+ lines.append(' </thead>')
+ lines.append(' <tbody>')
+ for a in a11y:
+ lines.append(f' <tr><td>{a.get("title", "")}</td>'
+ f'<td class="status-fail">{a.get("score", 0):.0%}</td></tr>')
+ lines.append(' </tbody>')
+ lines.append(' </table>')
+ lines.append('')
+
+ # Opportunities
+ opps = mobile.get("opportunities", [])
+ if opps:
+ lines.append(f' <h3>Optimization Opportunities ({len(opps)})</h3>')
+ lines.append(' <table>')
+ lines.append(' <thead>')
+ lines.append(' <tr><th>Opportunity</th><th>Estimated Savings</th></tr>')
+ lines.append(' </thead>')
+ lines.append(' <tbody>')
+ for o in opps:
+ lines.append(f' <tr><td>{o.get("title", "")}</td>'
+ f'<td>{o.get("savings_ms", 0)}ms</td></tr>')
+ lines.append(' </tbody>')
+ lines.append(' </table>')
+ lines.append('')
+
+ lines.append('</div>')
+ return "\n".join(lines), fig_counter[0]
+
+
+def _build_gsc_section(gsc_data, chart_paths, section_num=3, fig_start=1):
+ """Build the GSC Search Performance section."""
+ fig_counter = [fig_start]
+
+ def next_fig():
+ n = fig_counter[0]
+ fig_counter[0] += 1
+ return n
+
+ lines = []
+ lines.append(f'\n<!-- {"=" * 55} {section_num}. SEARCH PERFORMANCE {"=" * 3} -->')
+ lines.append('<div class="section">')
+ lines.append(' <div class="section-header">')
+ lines.append(f' <h2>{section_num}. Search Console Performance</h2>')
+ lines.append(' </div>')
+ lines.append('')
+
+ totals = gsc_data.get("totals", {})
+ dr = gsc_data.get("date_range", {})
+
+ if totals:
+ domain = gsc_data.get("property", "?")
+ lines.append(f' <p>Period: {dr.get("start", "?")} to {dr.get("end", "?")} '
+ f'| Property: {domain}</p>')
+ queries_count = gsc_data.get("row_count", 0)
+ impr_total = totals.get("impressions", 0)
+ lines.append(f' <p><strong>{domain}</strong> appeared in <strong>{queries_count}</strong> unique search queries '
+ f'with <strong>{impr_total:,}</strong> total impressions during this period.</p>')
+ lines.append('')
+
+ clicks_val = f'{totals.get("clicks", 0):,}'
+ impr_val = f'{totals.get("impressions", 0):,}'
+ ctr_val = f'{totals.get("ctr", 0)}%'
+ rows_val = str(gsc_data.get("row_count", 0))
+
+ # Metric cards in single row
+ lines.append(f' <h3>{section_num}.1 Key Metrics</h3>')
+ lines.append(' <div class="four-col">')
+ lines.append(f' <div class="col">{_metric_card(clicks_val, "Total Clicks", BRAND["primary"])}</div>')
+ lines.append(f' <div class="col">{_metric_card(impr_val, "Total Impressions", BRAND["secondary"])}</div>')
+ lines.append(f' <div class="col">{_metric_card(ctr_val, "Average CTR", BRAND["accent"])}</div>')
+ lines.append(f' <div class="col">{_metric_card(rows_val, "Queries Found", BRAND["dark"])}</div>')
+ lines.append(' </div>')
+ lines.append(' <hr class="divider">')
+ lines.append('')
+
+ # Top queries chart
+ queries_path = chart_paths.get("top_queries_path", "")
+ if queries_path:
+ lines.append(f' <h3>{section_num}.2 Top Queries by Impressions</h3>')
+ lines.append(_chart_html(
+ queries_path,
+ "Top search queries ranked by impression volume from Google Search Console (28-day period).",
+ next_fig(),
+ "Top queries bar chart",
+ ))
+
+ # Top queries table
+ rows = gsc_data.get("rows", [])
+ if rows:
+ lines.append(f' <h3>{section_num}.3 Query Detail Table</h3>')
+ lines.append(' <table>')
+ lines.append(' <thead>')
+ lines.append(' <tr><th>#</th><th>Query</th><th>Clicks</th>'
+ '<th>Impressions</th><th>CTR</th><th>Position</th></tr>')
+ lines.append(' </thead>')
+ lines.append(' <tbody>')
+ sorted_rows = sorted(rows, key=lambda r: r.get("impressions", 0), reverse=True)
+ for i, r in enumerate(sorted_rows[:15], 1):
+ query = r.get("query", r.get("keys", ["?"])[0])
+ pos = r.get("position", 0)
+ pos_cls = ("status-pass" if pos <= 3
+ else ("status-warn" if pos <= 10 else "status-fail"))
+ lines.append(f' <tr><td>{i}</td><td>{query}</td>'
+ f'<td>{r.get("clicks", 0)}</td>'
+ f'<td>{r.get("impressions", 0):,}</td>')
+ lines.append(f' <td>{r.get("ctr", 0)}%</td>'
+ f'<td class="{pos_cls}">{pos:.1f}</td></tr>')
+ lines.append(' </tbody>')
+ lines.append(' </table>')
+ lines.append('')
+
+ # Position analysis
+ if rows:
+ top3 = len([r for r in rows if r.get("position", 99) <= 3])
+ top10 = len([r for r in rows if r.get("position", 99) <= 10])
+ beyond = len([r for r in rows if r.get("position", 99) > 10])
+ lines.append(f' <h3>{section_num}.4 Query Position Analysis</h3>')
+ lines.append(' <div class="two-col">')
+ lines.append(f' <div class="col">')
+ lines.append(_metric_card(str(top3), "Queries in Top 3", BRAND["success"]))
+ lines.append(f' </div>')
+ lines.append(f' <div class="col">')
+ lines.append(_metric_card(str(top10), "Queries in Top 10", BRAND["warning"]))
+ lines.append(f' </div>')
+ lines.append(' </div>')
+ if beyond:
+ lines.append(f' <p>{beyond} queries rank beyond position 10 '
+ f'and may benefit from content optimization.</p>')
+ lines.append('')
+
+ # Quick wins
+ qw = gsc_data.get("quick_wins", [])
+ if qw:
+ lines.append(f' <h3>{section_num}.5 Quick Wins ({len(qw)} opportunities)</h3>')
+ lines.append(' <div class="highlight">These queries rank at position 4-10 with '
+ 'high impressions. A small ranking improvement could yield significant '
+ 'traffic gains.</div>')
+ lines.append(' <table>')
+ lines.append(' <thead>')
+ lines.append(' <tr><th>Query</th><th>Position</th>'
+ '<th>Impressions</th><th>Clicks</th></tr>')
+ lines.append(' </thead>')
+ lines.append(' <tbody>')
+ for w in qw:
+ query = w.get("keys", ["?"])[0] if w.get("keys") else w.get("query", "?")
+ lines.append(f' <tr><td>{query}</td>'
+ f'<td>{w.get("position", 0):.1f}</td>'
+ f'<td>{w.get("impressions", 0):,}</td>'
+ f'<td>{w.get("clicks", 0)}</td></tr>')
+ lines.append(' </tbody>')
+ lines.append(' </table>')
+ lines.append('')
+
+ lines.append(' <p class="data-freshness">Search Analytics data has a 2-3 day lag. '
+ 'Data available for ~16 months.</p>')
+ lines.append('</div>')
+ return "\n".join(lines), fig_counter[0]
+
+
+def _build_indexation_section(inspect_data, chart_paths, section_num=4, fig_start=1):
+ """Build the Indexation Status section."""
+ fig_counter = [fig_start]
+
+ def next_fig():
+ n = fig_counter[0]
+ fig_counter[0] += 1
+ return n
+
+ lines = []
+ lines.append(f'\n<!-- {"=" * 55} {section_num}. INDEXATION STATUS {"=" * 3} -->')
+ lines.append('<div class="section">')
+ lines.append(' <div class="section-header">')
+ lines.append(f' <h2>{section_num}. Indexation Status</h2>')
+ lines.append(' </div>')
+ lines.append('')
+
+ summary = inspect_data.get("summary", {})
+ total = inspect_data.get("total", 0)
+
+ if summary:
+ # Donut chart
+ idx_path = chart_paths.get("index_status_path", "")
+ if idx_path:
+ fig_n = next_fig()
+ lines.append(f' <h3>{section_num}.1 Index Coverage Overview</h3>')
+ lines.append(f' <div class="chart-container">')
+ lines.append(f' <img src="file://{idx_path}" style="width: 70%;" alt="Index status donut chart">')
+ lines.append(f' <div class="chart-caption">Figure {fig_n}: URL indexation status distribution from Google URL Inspection API.</div>')
+ lines.append(f' </div>')
+
+ # Summary cards
+ lines.append(f' <p>Total URLs inspected: <strong>{total}</strong></p>')
+ lines.append(' <div class="two-col">')
+ lines.append(f' <div class="col">')
+ lines.append(_metric_card(summary.get("pass", 0), "Indexed", BRAND["success"]))
+ lines.append(f' </div>')
+ lines.append(f' <div class="col">')
+ lines.append(_metric_card(summary.get("fail", 0), "Not Indexed", BRAND["danger"]))
+ lines.append(f' </div>')
+ lines.append(' </div>')
+ lines.append('')
+
+ indexed = summary.get("pass", 0)
+ not_indexed = summary.get("fail", 0)
+ if total > 0:
+ rate = round((indexed / total) * 100, 1)
+ lines.append(f' <p><strong>Index Rate:</strong> {rate}% of inspected URLs are indexed by Google.</p>')
+ if total > 0 and indexed > 0:
+ pct = (indexed / total) * 100
+ cls = "success-box" if pct >= 90 else ("highlight" if pct >= 70 else "critical-box")
+ lines.append(f' <div class="{cls}"><strong>Index Rate:</strong> '
+ f'{pct:.0f}% of inspected URLs are indexed.</div>')
+ lines.append('')
+
+ # Per-URL results table
+ results = inspect_data.get("results", [])
+ if results:
+ lines.append(f' <h3>{section_num}.2 Per-URL Results</h3>')
+ lines.append(' <table>')
+ lines.append(' <thead>')
+ lines.append(' <tr><th>URL</th><th>Verdict</th>'
+ '<th>Coverage State</th><th>Last Crawl</th></tr>')
+ lines.append(' </thead>')
+ lines.append(' <tbody>')
+ for r in results:
+ verdict = r.get("verdict", "?")
+ cls = ("status-pass" if verdict == "PASS"
+ else ("status-fail" if verdict == "FAIL" else ""))
+ idx = r.get("index_status", {})
+ cov = idx.get("coverage_state", r.get("error", "N/A"))
+ crawl = idx.get("last_crawl_time", "N/A")
+ if crawl and crawl != "N/A":
+ crawl = crawl[:10]
+ url_display = r.get("url", "?")
+ lines.append(f' <tr><td style="word-break:break-all;font-size:8pt;">'
+ f'{url_display}</td>')
+ lines.append(f' <td class="{cls}">{verdict}</td>'
+ f'<td>{cov}</td><td>{crawl}</td></tr>')
+ lines.append(' </tbody>')
+ lines.append(' </table>')
+ lines.append('')
+
+ # Rich results
+ rich = inspect_data.get("rich_results", [])
+ if rich:
+ lines.append(f' <h3>{section_num}.3 Rich Results Detected</h3>')
+ lines.append(' <table>')
+ lines.append(' <thead>')
+ lines.append(' <tr><th>URL</th><th>Rich Result Type</th></tr>')
+ lines.append(' </thead>')
+ lines.append(' <tbody>')
+ for rr in rich:
+ lines.append(f' <tr><td style="word-break:break-all;font-size:8pt;">'
+ f'{rr.get("url", "?")}</td>'
+ f'<td>{rr.get("type", "?")}</td></tr>')
+ lines.append(' </tbody>')
+ lines.append(' </table>')
+ lines.append('')
+
+ lines.append(' <p class="data-freshness">URL Inspection API: '
+ '2,000 inspections/day per property.</p>')
+ lines.append('</div>')
+ return "\n".join(lines), fig_counter[0]
+
+
+def _build_recommendations(data, section_num=5):
+ """Build prioritized recommendations section based on discovered issues."""
+ lines = []
+ lines.append(f'\n<!-- {"=" * 55} {section_num}. RECOMMENDATIONS {"=" * 3} -->')
+ lines.append('<div class="section">')
+ lines.append(' <div class="section-header">')
+ lines.append(f' <h2>{section_num}. Recommendations</h2>')
+ lines.append(' </div>')
+ lines.append('')
+ lines.append(' <p>Prioritized action items based on the data collected. '
+ 'Items are ranked by expected impact on search visibility and user experience.</p>')
+ lines.append('')
+
+ item_num = 0
+
+ # Collect critical items
+ critical_items = []
+ psi = data.get("psi", {})
+ mobile = psi.get("psi", {}).get("mobile", psi) if isinstance(psi, dict) else {}
+
+ perf = mobile.get("lighthouse_scores", {}).get("performance")
+ if perf is not None and perf < 50:
+ critical_items.append(
+ ("Improve Lighthouse Performance Score", "Medium (2-4 hrs)",
+ f"Current score is {perf}/100. Focus on reducing Largest Contentful Paint "
+ f"and Total Blocking Time. Defer non-critical JavaScript and optimize images.")
+ )
+
+ seo_failed = [a for a in mobile.get("seo_audits", []) if not a.get("pass")]
+ for a in seo_failed[:2]:
+ critical_items.append(
+ (f"Fix SEO Issue: {a.get('title', 'Unknown')}", "Low (30 min)",
+ "This Lighthouse SEO check is failing. Address it to ensure proper crawling "
+ "and indexing by search engines.")
+ )
+
+ inspect = data.get("inspection", {})
+ not_indexed = inspect.get("summary", {}).get("fail", 0)
+ if not_indexed:
+ critical_items.append(
+ (f"Resolve {not_indexed} Non-Indexed URL(s)", "Medium (2-4 hrs)",
+ "These pages are not appearing in Google's index. Review coverage state, "
+ "fix crawl errors, and request re-indexing via Search Console.")
+ )
+
+ if critical_items:
+ lines.append(f' <h3><span class="priority-tag priority-critical">CRITICAL</span> '
+ f'Fix Immediately</h3>')
+ for title, effort, desc in critical_items:
+ item_num += 1
+ lines.append(f' <div class="action-item critical">')
+ lines.append(f' <h4>{item_num}. {title} '
+ f'<span class="effort">Effort: {effort}</span></h4>')
+ lines.append(f' <p>{desc}</p>')
+ lines.append(f' </div>')
+ lines.append('')
+
+ # High priority items
+ high_items = []
+ failed_audits = mobile.get("failed_audits", [])
+ top_fails = sorted(failed_audits, key=lambda a: a.get("score", 1))[:5]
+ for a in top_fails:
+ if a.get("score", 1) < 0.5:
+ high_items.append(
+ (f"Address: {a.get('title', 'Unknown')}", "Medium (1-2 hrs)",
+ f"Score: {a['score']:.0%}. {a.get('display', 'Review and optimize this audit.')}")
+ )
+
+ opps = mobile.get("opportunities", [])
+ for o in opps[:3]:
+ savings = o.get("savings_ms", 0)
+ if savings:
+ high_items.append(
+ (f"{o.get('title', 'Optimization')}", "Medium (2-4 hrs)",
+ f"Potential savings of ~{savings}ms. Implement this to improve page load speed.")
+ )
+
+ gsc = data.get("gsc", {})
+ qw = gsc.get("quick_wins", [])
+ if qw:
+ high_items.append(
+ (f"Optimize {len(qw)} Quick-Win Queries", "Medium (2-4 hrs)",
+ "These queries rank at positions 4-10 with high impressions. "
+ "Improve on-page SEO and content depth to push them into top 3.")
+ )
+
+ if high_items:
+ lines.append(f' <h3><span class="priority-tag priority-high">HIGH</span> '
+ f'Fix Within 1 Week</h3>')
+ for title, effort, desc in high_items:
+ item_num += 1
+ lines.append(f' <div class="action-item high">')
+ lines.append(f' <h4>{item_num}. {title} '
+ f'<span class="effort">Effort: {effort}</span></h4>')
+ lines.append(f' <p>{desc}</p>')
+ lines.append(f' </div>')
+ lines.append('')
+
+ # Medium priority items
+ medium_items = []
+ a11y = mobile.get("accessibility_audits", [])
+ if a11y:
+ medium_items.append(
+ (f"Fix {len(a11y)} Accessibility Issue(s)", "Low (30 min)",
+ "Accessibility improvements benefit SEO (Lighthouse score) and user experience. "
+ "Address failing accessibility audits.")
+ )
+
+ acc_score = mobile.get("lighthouse_scores", {}).get("accessibility")
+ if acc_score is not None and acc_score < 90 and not a11y:
+ medium_items.append(
+ ("Improve Accessibility Score", "Medium (2-4 hrs)",
+ f"Current score: {acc_score}/100. Run a detailed accessibility audit "
+ f"and address any violations.")
+ )
+
+ bp_score = mobile.get("lighthouse_scores", {}).get("best-practices")
+ if bp_score is not None and bp_score < 90:
+ medium_items.append(
+ ("Address Best Practices Issues", "Low (30 min)",
+ f"Current score: {bp_score}/100. Review browser console for errors, "
+ f"update deprecated APIs, and ensure HTTPS for all resources.")
+ )
+
+ if medium_items:
+ lines.append(f' <h3><span class="priority-tag priority-medium">MEDIUM</span> '
+ f'Fix Within 1 Month</h3>')
+ for title, effort, desc in medium_items:
+ item_num += 1
+ lines.append(f' <div class="action-item medium">')
+ lines.append(f' <h4>{item_num}. {title} '
+ f'<span class="effort">Effort: {effort}</span></h4>')
+ lines.append(f' <p>{desc}</p>')
+ lines.append(f' </div>')
+ lines.append('')
+
+ # If no recommendations were generated at all
+ if item_num == 0:
+ lines.append(' <div class="success-box"><strong>No critical issues detected.</strong> '
+ 'Continue monitoring Core Web Vitals and search performance regularly.</div>')
+ lines.append('')
+
+ # Implementation Roadmap
+ lines.append(' <hr class="divider">')
+ lines.append(' <h3>Implementation Roadmap</h3>')
+ lines.append(' <div class="roadmap-phase">')
+ lines.append(' <h4>Week 1 &mdash; Quick Wins</h4>')
+ lines.append(' <ul>')
+ if seo_failed:
+ lines.append(' <li>Fix failing Lighthouse SEO checks</li>')
+ if a11y:
+ lines.append(f' <li>Address {len(a11y)} accessibility issue(s)</li>')
+ bp_score_val = mobile.get("lighthouse_scores", {}).get("best-practices")
+ if bp_score_val is not None and bp_score_val < 90:
+ lines.append(' <li>Review and fix Best Practices issues</li>')
+ if not seo_failed and not a11y and (bp_score_val is None or bp_score_val >= 90):
+ lines.append(' <li>Verify all monitoring dashboards are active</li>')
+ lines.append(' </ul>')
+ lines.append(' </div>')
+ lines.append(' <div class="roadmap-phase">')
+ lines.append(' <h4>Week 2&ndash;3 &mdash; Performance &amp; Indexation</h4>')
+ lines.append(' <ul>')
+ if perf is not None and perf < 50:
+ lines.append(' <li>Optimize Largest Contentful Paint and Total Blocking Time</li>')
+ if not_indexed:
+ lines.append(f' <li>Resolve {not_indexed} non-indexed URL(s)</li>')
+ if opps:
+ lines.append(f' <li>Implement {len(opps)} performance optimization(s)</li>')
+ if (perf is None or perf >= 50) and not not_indexed and not opps:
+ lines.append(' <li>Maintain current performance levels and monitor trends</li>')
+ lines.append(' </ul>')
+ lines.append(' </div>')
+ lines.append(' <div class="roadmap-phase">')
+ lines.append(' <h4>Week 4 &mdash; Content &amp; Search Optimization</h4>')
+ lines.append(' <ul>')
+ if qw:
+ lines.append(f' <li>Optimize {len(qw)} quick-win queries for top-3 rankings</li>')
+ lines.append(' <li>Review and improve content depth for underperforming pages</li>')
+ lines.append(' <li>Set up ongoing monitoring and reporting cadence</li>')
+ lines.append(' </ul>')
+ lines.append(' </div>')
+ lines.append('')
+
+ lines.append('</div>')
+ return "\n".join(lines)
+
+
+def _build_methodology_footer(domain, timestamp):
+ """Build the Data Sources & Methodology footer section."""
+ return (
+ f'\n<!-- {"=" * 55} DATA SOURCES & METHODOLOGY {"=" * 3} -->\n'
+ f'<div class="section" style="text-align: center; padding-top: 15mm;">\n'
+ f' <hr class="divider">\n'
+ f' <h3 style="text-align: left;">Data Sources &amp; Methodology</h3>\n'
+ f' <table>\n'
+ f' <thead>\n'
+ f' <tr><th>Source</th><th>Description</th><th>Update Frequency</th></tr>\n'
+ f' </thead>\n'
+ f' <tbody>\n'
+ f' <tr><td>PageSpeed Insights API</td>\n'
+ f' <td>Lighthouse lab audit (mobile emulation, Moto G Power, slow 4G)</td>\n'
+ f' <td>Real-time</td></tr>\n'
+ f' <tr><td>Chrome UX Report (CrUX)</td>\n'
+ f' <td>28-day rolling field data from real Chrome users</td>\n'
+ f' <td>Daily ~04:00 UTC</td></tr>\n'
+ f' <tr><td>CrUX History API</td>\n'
+ f' <td>25-week p75 trend data per metric</td>\n'
+ f' <td>Weekly</td></tr>\n'
+ f' <tr><td>Google Search Console</td>\n'
+ f' <td>Search Analytics (clicks, impressions, CTR, position)</td>\n'
+ f' <td>2-3 day lag</td></tr>\n'
+ f' <tr><td>URL Inspection API</td>\n'
+ f' <td>Per-URL index status, coverage state, crawl info</td>\n'
+ f' <td>Real-time (2,000/day)</td></tr>\n'
+ f' </tbody>\n'
+ f' </table>\n'
+ f' <p style="color: #94a3b8; font-size: 9pt; margin-top: 5mm;">\n'
+ f' Report generated by Claude SEO &mdash; Google SEO Intelligence Skill &mdash; '
+ f'{timestamp}<br>\n'
+ f' Methodology based on Google Web Vitals thresholds, Search Console documentation, '
+ f'and Lighthouse scoring algorithms.\n'
+ f' </p>\n'
+ f'</div>\n'
+ )
+
+
+# ─── Report Assemblers ───────────────────────────────────────────────────────
+
+def generate_report(report_type, data, domain, output_dir, output_format="pdf"):
+ """
+ Generate a complete professional PDF/HTML report.
+
+ Args:
+ report_type: 'cwv-audit', 'gsc-performance', 'indexation', or 'full'.
+ data: Dictionary with all input data.
+ domain: Domain name for the report header.
+ output_dir: Directory for output files.
+ output_format: 'pdf', 'html', or 'both'.
+
+ Returns:
+ Dictionary with output paths.
+ """
+ output_dir = Path(output_dir)
+ charts_dir = output_dir / "charts"
+ charts_dir.mkdir(parents=True, exist_ok=True)
+
+ timestamp = datetime.now().strftime("%B %d, %Y")
+ timestamp_short = datetime.now().strftime("%Y-%m-%d %H:%M")
+ result = {"report_type": report_type, "domain": domain, "files": [], "error": None}
+
+ # ── Generate Charts ──────────────────────────────────────────────────────
+
+ chart_paths = {}
+
+ if report_type in ("cwv-audit", "full"):
+ psi = data.get("psi", data)
+ mobile = psi.get("psi", {}).get("mobile", psi) if isinstance(psi, dict) else {}
+ path = chart_lighthouse_gauges(mobile, charts_dir)
+ if path:
+ chart_paths["gauges_path"] = path
+
+ crux = data.get("crux", {})
+ path = chart_cwv_distributions({"crux": crux} if crux else data, charts_dir)
+ if path:
+ chart_paths["distributions_path"] = path
+
+ history = data.get("crux_history", {})
+ if history and not history.get("error"):
+ path = chart_cwv_timeline(history, charts_dir)
+ if path:
+ chart_paths["timeline_path"] = path
+
+ if report_type in ("gsc-performance", "full"):
+ gsc = data.get("gsc", data)
+ path = chart_top_queries(gsc, charts_dir)
+ if path:
+ chart_paths["top_queries_path"] = path
+
+ if report_type in ("indexation", "full"):
+ inspect = data.get("inspection", data)
+ path = chart_index_status(inspect, charts_dir)
+ if path:
+ chart_paths["index_status_path"] = path
+
+ # ── Build HTML Sections ──────────────────────────────────────────────────
+
+ sections = []
+ fig_num = 1
+
+ # ── CWV-AUDIT report ─────────────────────────────────────────────────────
+ if report_type == "cwv-audit":
+ mobile = data.get("psi", data)
+ if isinstance(mobile, dict):
+ mobile = mobile.get("psi", {}).get("mobile", mobile)
+ perf_score = mobile.get("lighthouse_scores", {}).get("performance") if isinstance(mobile, dict) else None
+
+ sections.append(_build_title_page(
+ domain, "Core Web Vitals Audit",
+ "Performance &amp; User Experience Analysis",
+ score=perf_score,
+ score_label="Lighthouse Performance Score",
+ meta_items=[timestamp, "PageSpeed Insights + CrUX"],
+ ))
+
+ # TOC
+ toc_sections = [
+ {"num": 1, "title": "Executive Summary", "subs": [
+ "Key Metrics &amp; Critical Issues",
+ ]},
+ {"num": 2, "title": "Core Web Vitals &amp; Performance", "score": perf_score, "subs": [
+ "Lighthouse Scores",
+ "Lab Metrics",
+ "CrUX Field Data",
+ "Failed Audits &amp; SEO Checks",
+ ]},
+ {"num": 3, "title": "Recommendations", "subs": [
+ "Prioritized Action Items",
+ ]},
+ {"num": 4, "title": "Data Sources &amp; Methodology", "subs": []},
+ ]
+ sections.append(_build_toc(toc_sections))
+
+ sections.append(_build_executive_summary(domain, timestamp, data, report_type))
+
+ cwv_html, fig_num = _build_cwv_section(
+ data, data.get("crux", {}), chart_paths,
+ data.get("crux_history"), section_num=2,
+ )
+ sections.append(cwv_html)
+
+ sections.append(_build_recommendations(data, section_num=3))
+ sections.append(_build_methodology_footer(domain, timestamp))
+
+ # ── GSC-PERFORMANCE report ───────────────────────────────────────────────
+ elif report_type == "gsc-performance":
+ gsc = data.get("gsc", data)
+ clicks = gsc.get("totals", {}).get("clicks", 0)
+
+ sections.append(_build_title_page(
+ domain, "Search Console Performance",
+ "Google Search Analytics Report",
+ score=f"{clicks:,}",
+ score_label="Total Clicks",
+ meta_items=[timestamp, "Google Search Console API"],
+ ))
+
+ toc_sections = [
+ {"num": 1, "title": "Executive Summary", "subs": [
+ "Key Metrics &amp; Quick Wins",
+ ]},
+ {"num": 2, "title": "Search Console Performance", "subs": [
+ "Key Metrics",
+ "Top Queries by Clicks",
+ "Query Detail Table",
+ "Position Analysis &amp; Quick Wins",
+ ]},
+ {"num": 3, "title": "Recommendations", "subs": [
+ "Prioritized Action Items",
+ ]},
+ {"num": 4, "title": "Data Sources &amp; Methodology", "subs": []},
+ ]
+ sections.append(_build_toc(toc_sections))
+
+ sections.append(_build_executive_summary(domain, timestamp, data, report_type))
+
+ gsc_html, fig_num = _build_gsc_section(gsc, chart_paths, section_num=2)
+ sections.append(gsc_html)
+
+ sections.append(_build_recommendations(data, section_num=3))
+ sections.append(_build_methodology_footer(domain, timestamp))
+
+ # ── INDEXATION report ────────────────────────────────────────────────────
+ elif report_type == "indexation":
+ inspect = data.get("inspection", data)
+ total = inspect.get("total", 0)
+
+ sections.append(_build_title_page(
+ domain, "Indexation Status Report",
+ "URL Index Coverage Analysis",
+ score=total,
+ score_label="URLs Inspected",
+ meta_items=[timestamp, "URL Inspection API"],
+ ))
+
+ toc_sections = [
+ {"num": 1, "title": "Executive Summary", "subs": [
+ "Index Coverage Overview",
+ ]},
+ {"num": 2, "title": "Indexation Status", "subs": [
+ "Index Coverage Overview",
+ "Per-URL Results",
+ ]},
+ {"num": 3, "title": "Recommendations", "subs": [
+ "Prioritized Action Items",
+ ]},
+ {"num": 4, "title": "Data Sources &amp; Methodology", "subs": []},
+ ]
+ sections.append(_build_toc(toc_sections))
+
+ sections.append(_build_executive_summary(domain, timestamp, data, report_type))
+
+ idx_html, fig_num = _build_indexation_section(inspect, chart_paths, section_num=2)
+ sections.append(idx_html)
+
+ sections.append(_build_recommendations(data, section_num=3))
+ sections.append(_build_methodology_footer(domain, timestamp))
+
+ # ── FULL report ──────────────────────────────────────────────────────────
+ elif report_type == "full":
+ psi = data.get("psi", {})
+ mobile = psi.get("psi", {}).get("mobile", psi) if isinstance(psi, dict) else {}
+ perf_score = mobile.get("lighthouse_scores", {}).get("performance") if isinstance(mobile, dict) else None
+
+ sections.append(_build_title_page(
+ domain, "Google SEO Intelligence Report",
+ "Comprehensive Analysis",
+ score=perf_score,
+ score_label="Lighthouse Performance Score" if perf_score else None,
+ meta_items=[timestamp, "All Google APIs"],
+ ))
+
+ # Build TOC dynamically based on available data
+ toc_sections = [
+ {"num": 1, "title": "Executive Summary", "subs": [
+ "Key Metrics, Critical Issues &amp; Quick Wins",
+ ]},
+ ]
+ sec_num = 2
+ if data.get("psi") or data.get("crux"):
+ toc_sections.append({
+ "num": sec_num, "title": "Core Web Vitals &amp; Performance",
+ "score": perf_score, "subs": [
+ "Lighthouse Scores &amp; Lab Metrics",
+ "CrUX Field Data &amp; Trends",
+ "Failed Audits &amp; Opportunities",
+ ],
+ })
+ sec_num += 1
+ if data.get("gsc"):
+ toc_sections.append({
+ "num": sec_num, "title": "Search Console Performance", "subs": [
+ "Key Metrics &amp; Top Queries",
+ "Position Analysis &amp; Quick Wins",
+ ],
+ })
+ sec_num += 1
+ if data.get("inspection"):
+ toc_sections.append({
+ "num": sec_num, "title": "Indexation Status", "subs": [
+ "Index Coverage &amp; Per-URL Results",
+ ],
+ })
+ sec_num += 1
+ toc_sections.append({
+ "num": sec_num, "title": "Recommendations", "subs": [
+ "Prioritized Action Items",
+ ],
+ })
+ rec_num = sec_num
+ sec_num += 1
+ toc_sections.append({
+ "num": sec_num, "title": "Data Sources &amp; Methodology", "subs": [],
+ })
+
+ sections.append(_build_toc(toc_sections))
+ sections.append(_build_executive_summary(domain, timestamp, data, report_type))
+
+ current_sec = 2
+ if data.get("psi") or data.get("crux"):
+ cwv_html, fig_num = _build_cwv_section(
+ data.get("psi", {}), data.get("crux", {}), chart_paths,
+ data.get("crux_history"), section_num=current_sec,
+ )
+ sections.append(cwv_html)
+ current_sec += 1
+
+ if data.get("gsc"):
+ gsc_html, fig_num = _build_gsc_section(
+ data["gsc"], chart_paths,
+ section_num=current_sec, fig_start=fig_num,
+ )
+ sections.append(gsc_html)
+ current_sec += 1
+
+ if data.get("inspection"):
+ idx_html, fig_num = _build_indexation_section(
+ data["inspection"], chart_paths,
+ section_num=current_sec, fig_start=fig_num,
+ )
+ sections.append(idx_html)
+ current_sec += 1
+
+ sections.append(_build_recommendations(data, section_num=rec_num))
+ sections.append(_build_methodology_footer(domain, timestamp))
+
+ # ── Assemble Final HTML ──────────────────────────────────────────────────
+
+ css = _build_css(domain)
+ body = "\n".join(sections)
+ html_content = (
+ f'<!DOCTYPE html>\n'
+ f'<html lang="en">\n'
+ f'<head>\n'
+ f'<meta charset="UTF-8">\n'
+ f'<style>\n'
+ f'{css}\n'
+ f'</style>\n'
+ f'</head>\n'
+ f'<body>\n'
+ f'{body}\n'
+ f'</body>\n'
+ f'</html>\n'
+ )
+
+ # ── Write Output Files ───────────────────────────────────────────────────
+
+ safe_domain = domain.replace(":", "_").replace("/", "_")
+ base_name = f"Google-SEO-Report-{safe_domain}-{report_type}"
+
+ if output_format in ("html", "both"):
+ html_path = output_dir / f"{base_name}.html"
+ with open(html_path, "w", encoding="utf-8") as f:
+ f.write(html_content)
+ result["files"].append(str(html_path))
+
+ if output_format in ("pdf", "both"):
+ pdf_path = output_dir / f"{base_name}.pdf"
+ try:
+ HTML(string=html_content).write_pdf(str(pdf_path))
+ result["files"].append(str(pdf_path))
+ # Post-generation review
+ review = _review_pdf(str(pdf_path), html_content)
+ if review:
+ result["review"] = review
+ except Exception as e:
+ result["error"] = f"PDF generation failed: {e}"
+
+ return result
+
+
+def _review_pdf(pdf_path: str, html_content: str) -> dict:
+ """
+ RULE: Always review the PDF before presenting to the user.
+ Check for common rendering issues.
+ """
+ review = {"issues": [], "page_count": None, "file_size_kb": None}
+
+ # File size
+ try:
+ size = os.path.getsize(pdf_path)
+ review["file_size_kb"] = round(size / 1024, 1)
+ except OSError:
+ pass
+
+ # Page count (if pypdf available)
+ try:
+ from pypdf import PdfReader
+ reader = PdfReader(pdf_path)
+ review["page_count"] = len(reader.pages)
+ except ImportError:
+ pass
+
+ # HTML-level checks
+ import re
+ # Check for empty chart containers (img with no src)
+ empty_imgs = re.findall(r'<img[^>]*src=""[^>]*>', html_content)
+ if empty_imgs:
+ review["issues"].append(f"{len(empty_imgs)} empty image tag(s) found")
+
+ # Check for very short sections (might appear as mostly whitespace)
+ sections = html_content.split('div class="section"')
+ for i, sec in enumerate(sections[1:], 1):
+ # Strip HTML tags to get text content
+ text_only = re.sub(r'<[^>]+>', '', sec[:2000])
+ text_only = re.sub(r'\s+', ' ', text_only).strip()
+ if len(text_only) < 50:
+ review["issues"].append(f"Section {i} has very little text content ({len(text_only)} chars)")
+
+ # Check for duplicate content
+ tables = re.findall(r'<table>.*?</table>', html_content, re.DOTALL)
+ if len(tables) != len(set(tables)):
+ review["issues"].append("Duplicate tables detected")
+
+ if not review["issues"]:
+ review["status"] = "PASS"
+ else:
+ review["status"] = f"WARN ({len(review['issues'])} issues)"
+
+ return review
+
+
+# ─── CLI ─────────────────────────────────────────────────────────────────────
+
+def main():
+ parser = argparse.ArgumentParser(
+ description="Google SEO Report Generator - Professional PDF/HTML reports"
+ )
+ parser.add_argument(
+ "--type", "-t",
+ choices=["cwv-audit", "gsc-performance", "indexation", "full"],
+ required=True,
+ help="Report type",
+ )
+ parser.add_argument("--data", "-d", help="Path to JSON data file (or pipe via stdin)")
+ parser.add_argument("--domain", required=True, help="Domain name for the report header")
+ parser.add_argument("--output-dir", "-o", default=".", help="Output directory (default: current)")
+ parser.add_argument(
+ "--format", "-f",
+ choices=["pdf", "html", "both"],
+ default="pdf",
+ help="Output format (default: pdf)",
+ )
+ parser.add_argument("--json", "-j", action="store_true", help="Output metadata as JSON")
+
+ args = parser.parse_args()
+
+ # Load data
+ if args.data:
+ try:
+ with open(args.data, "r") as f:
+ data = json.load(f)
+ except (json.JSONDecodeError, IOError) as e:
+ print(f"Error reading data file: {e}", file=sys.stderr)
+ sys.exit(1)
+ elif not sys.stdin.isatty():
+ try:
+ data = json.load(sys.stdin)
+ except json.JSONDecodeError as e:
+ print(f"Error parsing stdin JSON: {e}", file=sys.stderr)
+ sys.exit(1)
+ else:
+ print("Error: Provide --data file or pipe JSON via stdin.", file=sys.stderr)
+ sys.exit(1)
+
+ result = generate_report(
+ report_type=args.type,
+ data=data,
+ domain=args.domain,
+ output_dir=args.output_dir,
+ output_format=args.format,
+ )
+
+ if result.get("error"):
+ print(f"Error: {result['error']}", file=sys.stderr)
+
+ if args.json:
+ print(json.dumps(result, indent=2))
+ else:
+ for f in result.get("files", []):
+ print(f"Generated: {f}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/scripts/gsc_inspect.py b/scripts/gsc_inspect.py
new file mode 100644
index 0000000..8551870
--- /dev/null
+++ b/scripts/gsc_inspect.py
@@ -0,0 +1,340 @@
+#!/usr/bin/env python3
+"""
+Google Search Console URL Inspection API helper.
+
+Inspects URLs for indexing status, canonical selection, crawl info,
+mobile usability, and rich results. Supports single URL and batch mode.
+
+Usage:
+ python gsc_inspect.py https://example.com/page --site-url sc-domain:example.com
+ python gsc_inspect.py --batch urls.txt --site-url sc-domain:example.com
+ python gsc_inspect.py https://example.com/page --json
+"""
+
+import argparse
+import json
+import sys
+import time
+from typing import Optional
+
+try:
+ from googleapiclient.discovery import build
+except ImportError:
+ print(
+ "Error: google-api-python-client required. "
+ "Install with: pip install google-api-python-client",
+ file=sys.stderr,
+ )
+ sys.exit(1)
+
+try:
+ from google_auth import get_oauth_credentials, load_config
+except ImportError:
+ import os
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+ from google_auth import get_oauth_credentials, load_config
+
+GSC_SCOPES = ["https://www.googleapis.com/auth/webmasters.readonly"]
+
+# Daily limit per site
+DAILY_LIMIT = 2000
+QPM_LIMIT = 600
+
+
+def _build_inspection_service():
+ """Build the Search Console v1 service for URL Inspection."""
+ credentials = get_oauth_credentials(GSC_SCOPES)
+ if not credentials:
+ return None
+ try:
+ return build("searchconsole", "v1", credentials=credentials)
+ except Exception as e:
+ print(f"Error building service: {e}", file=sys.stderr)
+ return None
+
+
+def inspect_url(
+ inspection_url: str,
+ site_url: str,
+ language_code: str = "en",
+) -> dict:
+ """
+ Inspect a single URL via the GSC URL Inspection API.
+
+ Args:
+ inspection_url: The URL to inspect.
+ site_url: The GSC property (e.g., 'sc-domain:example.com').
+ language_code: Language for localized messages (default: 'en').
+
+ Returns:
+ Dictionary with inspection results including index status,
+ crawl info, canonical, mobile usability, and rich results.
+ """
+ result = {
+ "url": inspection_url,
+ "property": site_url,
+ "index_status": None,
+ "crawl_info": None,
+ "canonical": None,
+ "mobile_usability": None,
+ "rich_results": None,
+ "verdict": None,
+ "error": None,
+ }
+
+ service = _build_inspection_service()
+ if not service:
+ result["error"] = "Could not build GSC service. Check service account credentials."
+ return result
+
+ body = {
+ "inspectionUrl": inspection_url,
+ "siteUrl": site_url,
+ "languageCode": language_code,
+ }
+
+ try:
+ response = service.urlInspection().index().inspect(body=body).execute()
+ except Exception as e:
+ error_str = str(e)
+ if "403" in error_str:
+ result["error"] = (
+ f"Permission denied. Add the service account as an Owner "
+ f"in GSC property '{site_url}'."
+ )
+ elif "429" in error_str:
+ result["error"] = (
+ f"Rate limit exceeded. URL Inspection: {QPM_LIMIT} QPM / {DAILY_LIMIT} QPD per site."
+ )
+ elif "400" in error_str:
+ result["error"] = (
+ f"Invalid request. Ensure the URL '{inspection_url}' belongs to "
+ f"property '{site_url}'."
+ )
+ else:
+ result["error"] = f"URL Inspection API error: {e}"
+ return result
+
+ ir = response.get("inspectionResult", {})
+
+ # Index status
+ idx = ir.get("indexStatusResult", {})
+ result["verdict"] = idx.get("verdict", "VERDICT_UNSPECIFIED")
+ result["index_status"] = {
+ "verdict": idx.get("verdict"),
+ "coverage_state": idx.get("coverageState"),
+ "robots_txt_state": idx.get("robotsTxtState"),
+ "indexing_state": idx.get("indexingState"),
+ "page_fetch_state": idx.get("pageFetchState"),
+ "last_crawl_time": idx.get("lastCrawlTime"),
+ "crawled_as": idx.get("crawledAs"),
+ "referring_urls": idx.get("referringUrls", []),
+ }
+
+ # Canonical
+ result["canonical"] = {
+ "google_canonical": idx.get("googleCanonical"),
+ "user_canonical": idx.get("userCanonical"),
+ "match": idx.get("googleCanonical") == idx.get("userCanonical")
+ if idx.get("googleCanonical") and idx.get("userCanonical") else None,
+ }
+
+ # Mobile usability (deprecated April 2023 but may still return data)
+ mu = ir.get("mobileUsabilityResult", {})
+ if mu:
+ result["mobile_usability"] = {
+ "verdict": mu.get("verdict"),
+ "issues": [
+ {"type": issue.get("issueType"), "message": issue.get("message")}
+ for issue in mu.get("issues", [])
+ ],
+ }
+
+ # Rich results
+ rr = ir.get("richResultsResult", {})
+ if rr:
+ result["rich_results"] = {
+ "verdict": rr.get("verdict"),
+ "detected_items": [
+ {
+ "type": item.get("richResultType"),
+ "items": [
+ {"name": i.get("name"), "issues": i.get("issues", [])}
+ for i in item.get("items", [])
+ ],
+ }
+ for item in rr.get("detectedItems", [])
+ ],
+ }
+
+ return result
+
+
+def batch_inspect(
+ urls: list,
+ site_url: str,
+ delay: float = 1.0,
+ language_code: str = "en",
+) -> dict:
+ """
+ Batch inspect multiple URLs with rate limiting.
+
+ Args:
+ urls: List of URLs to inspect.
+ site_url: GSC property.
+ delay: Seconds between requests (default: 1.0 for safety).
+ language_code: Language code.
+
+ Returns:
+ Dictionary with results list and summary.
+ """
+ result = {
+ "property": site_url,
+ "total": len(urls),
+ "results": [],
+ "summary": {
+ "pass": 0,
+ "fail": 0,
+ "neutral": 0,
+ "error": 0,
+ },
+ "error": None,
+ }
+
+ if len(urls) > DAILY_LIMIT:
+ result["error"] = (
+ f"Batch size ({len(urls)}) exceeds daily limit ({DAILY_LIMIT}). "
+ f"Only the first {DAILY_LIMIT} URLs will be processed."
+ )
+ urls = urls[:DAILY_LIMIT]
+
+ for i, url in enumerate(urls):
+ url = url.strip()
+ if not url:
+ continue
+
+ print(f"Inspecting [{i + 1}/{len(urls)}]: {url}", file=sys.stderr)
+
+ inspection = inspect_url(url, site_url, language_code)
+ result["results"].append(inspection)
+
+ verdict = inspection.get("verdict", "")
+ if inspection.get("error"):
+ result["summary"]["error"] += 1
+ elif verdict == "PASS":
+ result["summary"]["pass"] += 1
+ elif verdict == "FAIL":
+ result["summary"]["fail"] += 1
+ else:
+ result["summary"]["neutral"] += 1
+
+ # Rate limiting
+ if i < len(urls) - 1:
+ time.sleep(delay)
+
+ return result
+
+
+def main():
+ parser = argparse.ArgumentParser(
+ description="Google Search Console URL Inspection API helper"
+ )
+ parser.add_argument("url", nargs="?", help="URL to inspect")
+ parser.add_argument(
+ "--site-url", "-s",
+ help="GSC property (e.g., sc-domain:example.com). Uses default from config if not specified.",
+ )
+ parser.add_argument(
+ "--batch", "-b",
+ help="File with URLs to inspect (one per line)",
+ )
+ parser.add_argument(
+ "--delay",
+ type=float,
+ default=1.0,
+ help="Delay between batch requests in seconds (default: 1.0)",
+ )
+ parser.add_argument("--json", "-j", action="store_true", help="Output as JSON")
+
+ args = parser.parse_args()
+
+ # Resolve site URL
+ site_url = args.site_url
+ if not site_url:
+ config = load_config()
+ site_url = config.get("default_property")
+ if not site_url:
+ print("Error: No site URL specified. Use --site-url or set default_property in config.", file=sys.stderr)
+ sys.exit(1)
+
+ if args.batch:
+ # Batch mode
+ try:
+ with open(args.batch, "r") as f:
+ urls = [line.strip() for line in f if line.strip()]
+ except IOError as e:
+ print(f"Error reading batch file: {e}", file=sys.stderr)
+ sys.exit(1)
+
+ result = batch_inspect(urls, site_url, delay=args.delay)
+ elif args.url:
+ result = inspect_url(args.url, site_url)
+ else:
+ parser.print_help()
+ sys.exit(1)
+
+ if args.json:
+ print(json.dumps(result, indent=2))
+ else:
+ if args.batch:
+ summary = result.get("summary", {})
+ print(f"=== URL Inspection Batch Results ===")
+ print(f"Property: {site_url}")
+ print(f"Total: {result.get('total', 0)} | Pass: {summary.get('pass', 0)} | Fail: {summary.get('fail', 0)} | Errors: {summary.get('error', 0)}")
+ print()
+ for r in result.get("results", []):
+ verdict = r.get("verdict", "?")
+ status = {"PASS": "OK", "FAIL": "FAIL", "NEUTRAL": "--"}.get(verdict, "ERR")
+ print(f" [{status}] {r.get('url')}")
+ if r.get("error"):
+ print(f" Error: {r['error']}")
+ elif verdict == "FAIL":
+ idx = r.get("index_status", {})
+ print(f" Coverage: {idx.get('coverage_state')} | Fetch: {idx.get('page_fetch_state')}")
+ else:
+ if result.get("error"):
+ print(f"Error: {result['error']}", file=sys.stderr)
+ sys.exit(1)
+
+ verdict = result.get("verdict", "?")
+ print(f"=== URL Inspection: {result.get('url')} ===")
+ print(f"Verdict: {verdict}")
+
+ idx = result.get("index_status", {})
+ if idx:
+ print(f"\nIndex Status:")
+ print(f" Coverage: {idx.get('coverage_state')}")
+ print(f" Robots.txt: {idx.get('robots_txt_state')}")
+ print(f" Indexing: {idx.get('indexing_state')}")
+ print(f" Page Fetch: {idx.get('page_fetch_state')}")
+ print(f" Last Crawl: {idx.get('last_crawl_time', 'N/A')}")
+ print(f" Crawled As: {idx.get('crawled_as')}")
+
+ canon = result.get("canonical", {})
+ if canon:
+ print(f"\nCanonical:")
+ print(f" Google: {canon.get('google_canonical', 'N/A')}")
+ print(f" User: {canon.get('user_canonical', 'N/A')}")
+ match = canon.get("match")
+ if match is not None:
+ print(f" Match: {'Yes' if match else 'MISMATCH'}")
+
+ rr = result.get("rich_results")
+ if rr and rr.get("detected_items"):
+ print(f"\nRich Results: {rr.get('verdict')}")
+ for item in rr.get("detected_items", []):
+ print(f" Type: {item.get('type')}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/scripts/gsc_query.py b/scripts/gsc_query.py
new file mode 100644
index 0000000..7385f2f
--- /dev/null
+++ b/scripts/gsc_query.py
@@ -0,0 +1,378 @@
+#!/usr/bin/env python3
+"""
+Google Search Console Search Analytics query helper.
+
+Queries the GSC Search Analytics API for clicks, impressions, CTR, and position
+data. Supports filtering by dimensions, auto-pagination, and quick-win detection.
+
+Usage:
+ python gsc_query.py --property sc-domain:example.com
+ python gsc_query.py --property sc-domain:example.com --days 90 --dimensions query
+ python gsc_query.py sitemaps --property sc-domain:example.com
+ python gsc_query.py sites
+"""
+
+import argparse
+import json
+import sys
+from datetime import datetime, timedelta
+from typing import Optional
+
+try:
+ from googleapiclient.discovery import build
+except ImportError:
+ print(
+ "Error: google-api-python-client required. "
+ "Install with: pip install google-api-python-client",
+ file=sys.stderr,
+ )
+ sys.exit(1)
+
+try:
+ from google_auth import get_oauth_credentials, load_config
+except ImportError:
+ import os
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+ from google_auth import get_oauth_credentials, load_config
+
+GSC_SCOPES = ["https://www.googleapis.com/auth/webmasters.readonly"]
+
+
+def _build_gsc_service():
+ """Build the Search Console API service."""
+ credentials = get_oauth_credentials(GSC_SCOPES)
+ if not credentials:
+ return None
+ try:
+ return build("searchconsole", "v1", credentials=credentials)
+ except Exception as e:
+ print(f"Error building GSC service: {e}", file=sys.stderr)
+ return None
+
+
+def query_search_analytics(
+ site_url: str,
+ start_date: Optional[str] = None,
+ end_date: Optional[str] = None,
+ dimensions: Optional[list] = None,
+ search_type: str = "web",
+ row_limit: int = 1000,
+ filters: Optional[list] = None,
+ data_state: str = "final",
+) -> dict:
+ """
+ Query GSC Search Analytics API.
+
+ Args:
+ site_url: GSC property (e.g., 'sc-domain:example.com' or 'https://example.com/').
+ start_date: Start date (YYYY-MM-DD). Default: 28 days ago.
+ end_date: End date (YYYY-MM-DD). Default: 3 days ago (data lag).
+ dimensions: List of dimensions: query, page, country, device, date, searchAppearance.
+ search_type: web, image, video, news, discover, googleNews.
+ row_limit: Max rows per request (1-25000). Auto-paginates if more.
+ filters: List of filter dicts with dimension, operator, expression.
+ data_state: 'final' or 'all' (includes fresh/unfinalized data).
+
+ Returns:
+ Dictionary with rows, totals, and quick_wins.
+ """
+ result = {
+ "property": site_url,
+ "rows": [],
+ "totals": {"clicks": 0, "impressions": 0, "ctr": 0, "position": 0},
+ "quick_wins": [],
+ "row_count": 0,
+ "error": None,
+ }
+
+ service = _build_gsc_service()
+ if not service:
+ result["error"] = "Could not build GSC service. Check service account credentials."
+ return result
+
+ if not start_date:
+ start_date = (datetime.now() - timedelta(days=28)).strftime("%Y-%m-%d")
+ if not end_date:
+ end_date = (datetime.now() - timedelta(days=3)).strftime("%Y-%m-%d")
+ if dimensions is None:
+ dimensions = ["query", "page"]
+
+ result["date_range"] = {"start": start_date, "end": end_date}
+
+ body = {
+ "startDate": start_date,
+ "endDate": end_date,
+ "dimensions": dimensions,
+ "type": search_type,
+ "rowLimit": min(row_limit, 25000),
+ "dataState": data_state,
+ }
+
+ if filters:
+ body["dimensionFilterGroups"] = [{"filters": filters}]
+
+ # Auto-paginate
+ all_rows = []
+ start_row = 0
+ page_size = min(row_limit, 25000)
+
+ try:
+ while True:
+ body["startRow"] = start_row
+ body["rowLimit"] = page_size
+
+ response = service.searchanalytics().query(
+ siteUrl=site_url, body=body
+ ).execute()
+
+ rows = response.get("rows", [])
+ all_rows.extend(rows)
+
+ if len(rows) < page_size:
+ break
+
+ start_row += page_size
+
+ # Safety: cap at 100,000 rows
+ if start_row >= 100000:
+ break
+
+ except Exception as e:
+ error_str = str(e)
+ if "403" in error_str:
+ result["error"] = (
+ f"Permission denied for property '{site_url}'. "
+ "Ensure the service account email is added as a user in "
+ "Google Search Console > Settings > Users and permissions."
+ )
+ elif "404" in error_str:
+ result["error"] = (
+ f"Property '{site_url}' not found. "
+ "Use 'sc-domain:example.com' for domain properties or "
+ "'https://example.com/' for URL-prefix properties."
+ )
+ else:
+ result["error"] = f"GSC API error: {e}"
+ return result
+
+ # Process rows
+ total_clicks = 0
+ total_impressions = 0
+
+ for row in all_rows:
+ keys = row.get("keys", [])
+ clicks = row.get("clicks", 0)
+ impressions = row.get("impressions", 0)
+ ctr = row.get("ctr", 0)
+ position = row.get("position", 0)
+
+ processed = {
+ "keys": keys,
+ "clicks": clicks,
+ "impressions": impressions,
+ "ctr": round(ctr * 100, 2),
+ "position": round(position, 1),
+ }
+
+ # Label keys by dimension name
+ for i, dim in enumerate(dimensions):
+ if i < len(keys):
+ processed[dim] = keys[i]
+
+ result["rows"].append(processed)
+ total_clicks += clicks
+ total_impressions += impressions
+
+ result["row_count"] = len(all_rows)
+ result["totals"]["clicks"] = total_clicks
+ result["totals"]["impressions"] = total_impressions
+ if total_impressions > 0:
+ result["totals"]["ctr"] = round((total_clicks / total_impressions) * 100, 2)
+
+ # Quick wins: position 4-10 with high impressions
+ if "query" in dimensions:
+ sorted_by_impressions = sorted(all_rows, key=lambda r: r.get("impressions", 0), reverse=True)
+ for row in sorted_by_impressions[:200]:
+ pos = row.get("position", 0)
+ if 4 <= pos <= 10 and row.get("impressions", 0) > 50:
+ result["quick_wins"].append({
+ "keys": row.get("keys", []),
+ "position": round(pos, 1),
+ "impressions": row.get("impressions", 0),
+ "clicks": row.get("clicks", 0),
+ "ctr": round(row.get("ctr", 0) * 100, 2),
+ "opportunity": "Position 4-10 with high impressions -- small ranking improvement yields significant traffic gain",
+ })
+
+ result["quick_wins"] = result["quick_wins"][:20]
+
+ return result
+
+
+def list_sitemaps(site_url: str) -> dict:
+ """
+ List sitemaps for a GSC property.
+
+ Args:
+ site_url: GSC property URL.
+
+ Returns:
+ Dictionary with sitemaps list.
+ """
+ result = {"property": site_url, "sitemaps": [], "error": None}
+
+ service = _build_gsc_service()
+ if not service:
+ result["error"] = "Could not build GSC service."
+ return result
+
+ try:
+ response = service.sitemaps().list(siteUrl=site_url).execute()
+ for sm in response.get("sitemap", []):
+ result["sitemaps"].append({
+ "path": sm.get("path"),
+ "last_submitted": sm.get("lastSubmitted"),
+ "is_pending": sm.get("isPending"),
+ "is_index": sm.get("isSitemapsIndex"),
+ "type": sm.get("type"),
+ "warnings": sm.get("warnings", 0),
+ "errors": sm.get("errors", 0),
+ "contents": sm.get("contents", []),
+ })
+ except Exception as e:
+ result["error"] = f"Error listing sitemaps: {e}"
+
+ return result
+
+
+def list_sites() -> dict:
+ """
+ List all verified GSC properties.
+
+ Returns:
+ Dictionary with sites list.
+ """
+ result = {"sites": [], "error": None}
+
+ service = _build_gsc_service()
+ if not service:
+ result["error"] = "Could not build GSC service."
+ return result
+
+ try:
+ response = service.sites().list().execute()
+ for site in response.get("siteEntry", []):
+ result["sites"].append({
+ "url": site.get("siteUrl"),
+ "permission": site.get("permissionLevel"),
+ })
+ except Exception as e:
+ result["error"] = f"Error listing sites: {e}"
+
+ return result
+
+
+def main():
+ parser = argparse.ArgumentParser(
+ description="Google Search Console Search Analytics query helper"
+ )
+ parser.add_argument(
+ "command",
+ nargs="?",
+ default="query",
+ choices=["query", "sitemaps", "sites"],
+ help="Command: query (default), sitemaps, sites",
+ )
+ parser.add_argument(
+ "--property", "-p",
+ help="GSC property (e.g., sc-domain:example.com). Uses default from config if not specified.",
+ )
+ parser.add_argument("--days", "-d", type=int, default=28, help="Number of days (default: 28)")
+ parser.add_argument("--start-date", help="Start date (YYYY-MM-DD)")
+ parser.add_argument("--end-date", help="End date (YYYY-MM-DD)")
+ parser.add_argument(
+ "--dimensions",
+ default="query,page",
+ help="Comma-separated dimensions (default: query,page)",
+ )
+ parser.add_argument("--type", default="web", help="Search type (default: web)")
+ parser.add_argument("--limit", type=int, default=1000, help="Row limit (default: 1000)")
+ parser.add_argument(
+ "--device",
+ choices=["desktop", "mobile", "tablet"],
+ help="Filter by device type",
+ )
+ parser.add_argument("--country", help="Filter by country (ISO 3166-1 alpha-3, e.g., USA)")
+ parser.add_argument("--json", "-j", action="store_true", help="Output as JSON")
+
+ args = parser.parse_args()
+
+ # Resolve property
+ prop = args.property
+ if not prop:
+ config = load_config()
+ prop = config.get("default_property")
+ if not prop and args.command != "sites":
+ print("Error: No property specified. Use --property or set default_property in config.", file=sys.stderr)
+ sys.exit(1)
+
+ if args.command == "sites":
+ result = list_sites()
+ elif args.command == "sitemaps":
+ result = list_sitemaps(prop)
+ else:
+ start = args.start_date or (datetime.now() - timedelta(days=args.days)).strftime("%Y-%m-%d")
+ end = args.end_date or (datetime.now() - timedelta(days=3)).strftime("%Y-%m-%d")
+ dims = [d.strip() for d in args.dimensions.split(",")]
+ filters = []
+ if args.device:
+ filters.append({
+ "dimension": "device",
+ "operator": "equals",
+ "expression": args.device.upper(),
+ })
+ if args.country:
+ filters.append({
+ "dimension": "country",
+ "operator": "equals",
+ "expression": args.country.upper(),
+ })
+ result = query_search_analytics(
+ prop, start_date=start, end_date=end,
+ dimensions=dims, search_type=args.type, row_limit=args.limit,
+ filters=filters if filters else None,
+ )
+
+ if result.get("error"):
+ print(f"Error: {result['error']}", file=sys.stderr)
+ if not args.json:
+ sys.exit(1)
+
+ if args.json:
+ print(json.dumps(result, indent=2))
+ else:
+ if args.command == "sites":
+ print("=== Verified GSC Properties ===")
+ for site in result.get("sites", []):
+ print(f" {site['url']} ({site['permission']})")
+ elif args.command == "sitemaps":
+ print(f"=== Sitemaps for {prop} ===")
+ for sm in result.get("sitemaps", []):
+ status = "pending" if sm.get("is_pending") else "processed"
+ print(f" {sm['path']} [{status}] errors={sm.get('errors', 0)} warnings={sm.get('warnings', 0)}")
+ else:
+ totals = result.get("totals", {})
+ print(f"=== Search Analytics: {prop} ===")
+ print(f"Period: {result.get('date_range', {}).get('start')} to {result.get('date_range', {}).get('end')}")
+ print(f"Clicks: {totals.get('clicks', 0):,} | Impressions: {totals.get('impressions', 0):,} | CTR: {totals.get('ctr', 0)}% | Rows: {result.get('row_count', 0)}")
+
+ qw = result.get("quick_wins", [])
+ if qw:
+ print(f"\nQuick Wins ({len(qw)} found):")
+ for w in qw[:10]:
+ keys = " | ".join(w.get("keys", []))
+ print(f" Pos {w['position']} | {w['impressions']:,} imp | {w['clicks']} clicks | {keys}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/scripts/indexing_notify.py b/scripts/indexing_notify.py
new file mode 100644
index 0000000..9acff83
--- /dev/null
+++ b/scripts/indexing_notify.py
@@ -0,0 +1,313 @@
+#!/usr/bin/env python3
+"""
+Google Indexing API v3 - notify Google of URL updates and removals.
+
+Publishes URL_UPDATED or URL_DELETED notifications. Supports single URL
+and batch mode (up to 200 URLs/day). Includes quota tracking.
+
+IMPORTANT: The Indexing API is officially restricted to pages with
+JobPosting or BroadcastEvent/VideoObject structured data. Google may
+process other page types but provides no guarantees.
+
+Usage:
+ python indexing_notify.py https://example.com/jobs/123
+ python indexing_notify.py https://example.com/jobs/123 --action URL_DELETED
+ python indexing_notify.py --batch urls.txt
+ python indexing_notify.py --status https://example.com/jobs/123
+"""
+
+import argparse
+import json
+import sys
+import time
+from typing import Optional
+
+try:
+ from googleapiclient.discovery import build
+ from googleapiclient.http import BatchHttpRequest
+except ImportError:
+ print(
+ "Error: google-api-python-client required. "
+ "Install with: pip install google-api-python-client",
+ file=sys.stderr,
+ )
+ sys.exit(1)
+
+try:
+ from google_auth import get_oauth_credentials
+except ImportError:
+ import os
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+ from google_auth import get_oauth_credentials
+
+INDEXING_SCOPES = ["https://www.googleapis.com/auth/indexing"]
+DAILY_QUOTA = 200
+
+SCOPE_WARNING = (
+ "NOTE: The Indexing API is officially for JobPosting and "
+ "BroadcastEvent/VideoObject pages only. Google may process other "
+ "page types but provides no guarantees."
+)
+
+
+def _build_indexing_service():
+ """Build the Indexing API v3 service."""
+ credentials = get_oauth_credentials(INDEXING_SCOPES)
+ if not credentials:
+ return None
+ try:
+ return build("indexing", "v3", credentials=credentials)
+ except Exception as e:
+ print(f"Error building Indexing service: {e}", file=sys.stderr)
+ return None
+
+
+def notify_url(
+ url: str,
+ action: str = "URL_UPDATED",
+) -> dict:
+ """
+ Publish a single URL notification to the Indexing API.
+
+ Args:
+ url: The URL to notify about.
+ action: 'URL_UPDATED' or 'URL_DELETED'.
+
+ Returns:
+ Dictionary with notification result.
+ """
+ result = {
+ "url": url,
+ "action": action,
+ "notify_time": None,
+ "error": None,
+ }
+
+ service = _build_indexing_service()
+ if not service:
+ result["error"] = (
+ "Could not build Indexing service. Ensure the service account has "
+ "'https://www.googleapis.com/auth/indexing' scope and is added as "
+ "Owner in Google Search Console for the target domain."
+ )
+ return result
+
+ body = {
+ "url": url,
+ "type": action,
+ }
+
+ try:
+ response = service.urlNotifications().publish(body=body).execute()
+ metadata = response.get("urlNotificationMetadata", {})
+ latest = metadata.get("latestUpdate", {}) or metadata.get("latestRemove", {})
+ result["notify_time"] = latest.get("notifyTime")
+ except Exception as e:
+ error_str = str(e)
+ if "403" in error_str:
+ result["error"] = (
+ "Permission denied. The service account must be added as an "
+ "Owner in Google Search Console for this domain. "
+ "Also ensure the Indexing API is enabled in your GCP project."
+ )
+ elif "429" in error_str:
+ result["error"] = (
+ f"Quota exceeded. Daily limit: {DAILY_QUOTA} publish requests. "
+ "Apply for a quota increase at https://developers.google.com/search/apis/indexing-api/v3/quota-increase"
+ )
+ elif "400" in error_str:
+ result["error"] = f"Invalid URL or request: {e}"
+ else:
+ result["error"] = f"Indexing API error: {e}"
+
+ return result
+
+
+def get_notification_metadata(url: str) -> dict:
+ """
+ Get the latest notification metadata for a URL.
+
+ Args:
+ url: The URL to check.
+
+ Returns:
+ Dictionary with latest update and remove timestamps.
+ """
+ result = {
+ "url": url,
+ "latest_update": None,
+ "latest_remove": None,
+ "error": None,
+ }
+
+ service = _build_indexing_service()
+ if not service:
+ result["error"] = "Could not build Indexing service."
+ return result
+
+ try:
+ response = service.urlNotifications().getMetadata(url=url).execute()
+ update = response.get("latestUpdate", {})
+ remove = response.get("latestRemove", {})
+
+ if update:
+ result["latest_update"] = {
+ "url": update.get("url"),
+ "type": update.get("type"),
+ "notify_time": update.get("notifyTime"),
+ }
+ if remove:
+ result["latest_remove"] = {
+ "url": remove.get("url"),
+ "type": remove.get("type"),
+ "notify_time": remove.get("notifyTime"),
+ }
+ except Exception as e:
+ if "404" in str(e):
+ result["error"] = "No notification metadata found for this URL."
+ else:
+ result["error"] = f"Error fetching metadata: {e}"
+
+ return result
+
+
+def batch_notify(
+ urls: list,
+ action: str = "URL_UPDATED",
+ delay: float = 0.5,
+) -> dict:
+ """
+ Batch notify multiple URLs with quota awareness.
+
+ Args:
+ urls: List of URLs.
+ action: 'URL_UPDATED' or 'URL_DELETED'.
+ delay: Seconds between requests.
+
+ Returns:
+ Dictionary with results and quota usage.
+ """
+ result = {
+ "action": action,
+ "total": len(urls),
+ "results": [],
+ "summary": {"success": 0, "error": 0},
+ "quota_warning": None,
+ "error": None,
+ }
+
+ if len(urls) > DAILY_QUOTA:
+ result["quota_warning"] = (
+ f"Batch size ({len(urls)}) exceeds daily quota ({DAILY_QUOTA}). "
+ f"Only the first {DAILY_QUOTA} URLs will be submitted."
+ )
+ urls = urls[:DAILY_QUOTA]
+
+ if len(urls) > 50:
+ result["quota_warning"] = (
+ f"Submitting {len(urls)} URLs will use {len(urls)}/{DAILY_QUOTA} "
+ f"of your daily quota."
+ )
+
+ for i, url in enumerate(urls):
+ url = url.strip()
+ if not url:
+ continue
+
+ print(f"Notifying [{i + 1}/{len(urls)}]: {url}", file=sys.stderr)
+
+ notification = notify_url(url, action)
+ result["results"].append(notification)
+
+ if notification.get("error"):
+ result["summary"]["error"] += 1
+ # Stop on quota errors
+ if "429" in str(notification.get("error", "")):
+ result["error"] = "Stopped: daily quota exceeded."
+ break
+ else:
+ result["summary"]["success"] += 1
+
+ if i < len(urls) - 1:
+ time.sleep(delay)
+
+ remaining = DAILY_QUOTA - result["summary"]["success"]
+ result["estimated_remaining_quota"] = max(0, remaining)
+
+ return result
+
+
+def main():
+ parser = argparse.ArgumentParser(
+ description="Google Indexing API v3 - URL notification helper"
+ )
+ parser.add_argument("url", nargs="?", help="URL to notify")
+ parser.add_argument(
+ "--action", "-a",
+ choices=["URL_UPDATED", "URL_DELETED"],
+ default="URL_UPDATED",
+ help="Notification type (default: URL_UPDATED)",
+ )
+ parser.add_argument("--batch", "-b", help="File with URLs (one per line)")
+ parser.add_argument("--status", help="Check notification status for a URL")
+ parser.add_argument(
+ "--delay",
+ type=float,
+ default=0.5,
+ help="Delay between batch requests in seconds (default: 0.5)",
+ )
+ parser.add_argument("--json", "-j", action="store_true", help="Output as JSON")
+
+ args = parser.parse_args()
+
+ if args.status:
+ result = get_notification_metadata(args.status)
+ elif args.batch:
+ print(SCOPE_WARNING, file=sys.stderr)
+ try:
+ with open(args.batch, "r") as f:
+ urls = [line.strip() for line in f if line.strip()]
+ except IOError as e:
+ print(f"Error reading batch file: {e}", file=sys.stderr)
+ sys.exit(1)
+ result = batch_notify(urls, args.action, delay=args.delay)
+ elif args.url:
+ print(SCOPE_WARNING, file=sys.stderr)
+ result = notify_url(args.url, args.action)
+ else:
+ parser.print_help()
+ sys.exit(1)
+
+ if args.json:
+ print(json.dumps(result, indent=2))
+ else:
+ if result.get("error"):
+ print(f"Error: {result['error']}", file=sys.stderr)
+
+ if args.status:
+ print(f"=== Notification Status: {args.status} ===")
+ update = result.get("latest_update")
+ remove = result.get("latest_remove")
+ if update:
+ print(f" Latest Update: {update.get('notify_time')} ({update.get('type')})")
+ if remove:
+ print(f" Latest Remove: {remove.get('notify_time')} ({remove.get('type')})")
+ if not update and not remove and not result.get("error"):
+ print(" No notifications found.")
+ elif args.batch:
+ summary = result.get("summary", {})
+ print(f"=== Batch Indexing Notification ===")
+ print(f"Action: {args.action}")
+ print(f"Total: {result.get('total', 0)} | Success: {summary.get('success', 0)} | Errors: {summary.get('error', 0)}")
+ print(f"Estimated remaining daily quota: {result.get('estimated_remaining_quota', '?')}")
+ if result.get("quota_warning"):
+ print(f"Warning: {result['quota_warning']}")
+ else:
+ if result.get("notify_time"):
+ print(f"Notified: {result['url']} ({result['action']}) at {result['notify_time']}")
+ elif not result.get("error"):
+ print(f"Notification sent for: {result['url']} ({result['action']})")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/scripts/keyword_planner.py b/scripts/keyword_planner.py
new file mode 100644
index 0000000..fb25c5f
--- /dev/null
+++ b/scripts/keyword_planner.py
@@ -0,0 +1,297 @@
+#!/usr/bin/env python3
+"""
+Google Ads API - Keyword Planner for SEO keyword research.
+
+Gold-standard source for keyword search volume, CPC, and competition data.
+Requires a Google Ads Manager account with a developer token.
+
+Usage:
+ python keyword_planner.py ideas "seo tools" --json
+ python keyword_planner.py volume "seo tools,seo audit,seo checker" --json
+ python keyword_planner.py forecast "seo tools" --json
+
+Prerequisites:
+ - Google Ads Manager account (can be free)
+ - Developer Token (apply at Google Ads API Center)
+ - OAuth credentials or service account
+ - google-ads Python library: pip install google-ads
+ - Config: ~/.config/claude-seo/google-api.json with:
+ {
+ "ads_developer_token": "YOUR_DEV_TOKEN",
+ "ads_customer_id": "123-456-7890",
+ "ads_login_customer_id": "123-456-7890"
+ }
+
+Note: Accounts without active ad spend receive bucketed volume ranges
+(e.g., "1K-10K") instead of exact numbers.
+"""
+
+import argparse
+import json
+import sys
+from typing import Optional
+
+try:
+ from google.ads.googleads.client import GoogleAdsClient
+ from google.ads.googleads.errors import GoogleAdsException
+ HAS_GOOGLE_ADS = True
+except ImportError:
+ HAS_GOOGLE_ADS = False
+
+try:
+ from google_auth import load_config
+except ImportError:
+ import os
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+ from google_auth import load_config
+
+
+def _build_ads_client() -> Optional[object]:
+ """Build Google Ads client from config."""
+ if not HAS_GOOGLE_ADS:
+ print(
+ "Error: google-ads library required. Install with: pip install google-ads",
+ file=sys.stderr,
+ )
+ return None
+
+ config = load_config()
+ dev_token = config.get("ads_developer_token")
+ customer_id = config.get("ads_customer_id", "").replace("-", "")
+ login_customer_id = config.get("ads_login_customer_id", "").replace("-", "")
+ oauth_client_path = config.get("oauth_client_path")
+
+ if not dev_token:
+ print(
+ "Error: No Google Ads developer token configured. "
+ "Add 'ads_developer_token' to ~/.config/claude-seo/google-api.json. "
+ "Get a token at: https://ads.google.com/aw/apicenter",
+ file=sys.stderr,
+ )
+ return None
+
+ if not customer_id:
+ print(
+ "Error: No Google Ads customer ID configured. "
+ "Add 'ads_customer_id' (format: 123-456-7890) to config.",
+ file=sys.stderr,
+ )
+ return None
+
+ try:
+ # Build from dict configuration
+ ads_config = {
+ "developer_token": dev_token,
+ "use_proto_plus": True,
+ }
+ if login_customer_id:
+ ads_config["login_customer_id"] = login_customer_id
+
+ # Try to use OAuth token if available
+ token_path = os.path.expanduser("~/.config/claude-seo/oauth-token.json")
+ if os.path.exists(token_path):
+ with open(token_path) as f:
+ token_data = json.load(f)
+ if oauth_client_path:
+ with open(os.path.expanduser(oauth_client_path)) as f:
+ client_data = json.load(f)
+ client_info = client_data.get("web", client_data.get("installed", {}))
+ ads_config["client_id"] = client_info.get("client_id")
+ ads_config["client_secret"] = client_info.get("client_secret")
+ ads_config["refresh_token"] = token_data.get("refresh_token")
+
+ client = GoogleAdsClient.load_from_dict(ads_config)
+ return client, customer_id
+
+ except Exception as e:
+ print(f"Error building Google Ads client: {e}", file=sys.stderr)
+ return None
+
+
+def generate_keyword_ideas(
+ seed_keywords: list,
+ language_id: str = "1000",
+ location_id: str = "2840",
+ limit: int = 50,
+) -> dict:
+ """
+ Generate keyword ideas from seed keywords.
+
+ Args:
+ seed_keywords: List of seed keyword strings.
+ language_id: Language ID (1000 = English).
+ location_id: Location ID (2840 = United States).
+ limit: Max results.
+
+ Returns:
+ Dictionary with keyword ideas and metrics.
+ """
+ result = {
+ "seed_keywords": seed_keywords,
+ "ideas": [],
+ "error": None,
+ }
+
+ client_data = _build_ads_client()
+ if not client_data:
+ result["error"] = "Could not build Google Ads client. Check config."
+ return result
+
+ client, customer_id = client_data
+
+ try:
+ kp_service = client.get_service("KeywordPlanIdeaService")
+ request = client.get_type("GenerateKeywordIdeasRequest")
+ request.customer_id = customer_id
+ request.language = f"languageConstants/{language_id}"
+ request.geo_target_constants.append(f"geoTargetConstants/{location_id}")
+ request.keyword_plan_network = client.enums.KeywordPlanNetworkEnum.GOOGLE_SEARCH
+ request.keyword_seed.keywords.extend(seed_keywords)
+
+ response = kp_service.generate_keyword_ideas(request=request)
+
+ for idea in response.results:
+ metrics = idea.keyword_idea_metrics
+ monthly_volumes = []
+ for mv in metrics.monthly_search_volumes:
+ monthly_volumes.append({
+ "year": mv.year,
+ "month": mv.month,
+ "volume": mv.monthly_searches,
+ })
+
+ result["ideas"].append({
+ "keyword": idea.text,
+ "avg_monthly_searches": metrics.avg_monthly_searches,
+ "competition": metrics.competition.name if metrics.competition else "UNSPECIFIED",
+ "competition_index": metrics.competition_index,
+ "low_top_of_page_bid": metrics.low_top_of_page_bid_micros / 1_000_000 if metrics.low_top_of_page_bid_micros else None,
+ "high_top_of_page_bid": metrics.high_top_of_page_bid_micros / 1_000_000 if metrics.high_top_of_page_bid_micros else None,
+ "monthly_volumes": monthly_volumes[-12:] if monthly_volumes else [],
+ })
+
+ if len(result["ideas"]) >= limit:
+ break
+
+ # Sort by volume descending
+ result["ideas"].sort(key=lambda k: k.get("avg_monthly_searches", 0) or 0, reverse=True)
+
+ except GoogleAdsException as e:
+ errors = [err.message for err in e.failure.errors]
+ result["error"] = f"Google Ads API error: {'; '.join(errors)}"
+ except Exception as e:
+ result["error"] = f"Keyword Planner error: {e}"
+
+ return result
+
+
+def get_keyword_volumes(
+ keywords: list,
+ language_id: str = "1000",
+ location_id: str = "2840",
+) -> dict:
+ """
+ Get search volume for specific keywords.
+
+ Args:
+ keywords: List of keywords to check.
+ language_id: Language ID.
+ location_id: Location ID.
+
+ Returns:
+ Dictionary with keyword metrics.
+ """
+ result = {
+ "keywords": [],
+ "error": None,
+ }
+
+ client_data = _build_ads_client()
+ if not client_data:
+ result["error"] = "Could not build Google Ads client."
+ return result
+
+ client, customer_id = client_data
+
+ try:
+ kp_service = client.get_service("KeywordPlanIdeaService")
+ request = client.get_type("GenerateKeywordHistoricalMetricsRequest")
+ request.customer_id = customer_id
+ request.keywords.extend(keywords)
+ request.language = f"languageConstants/{language_id}"
+ request.geo_target_constants.append(f"geoTargetConstants/{location_id}")
+ request.keyword_plan_network = client.enums.KeywordPlanNetworkEnum.GOOGLE_SEARCH
+
+ response = kp_service.generate_keyword_historical_metrics(request=request)
+
+ for kw_result in response.results:
+ metrics = kw_result.keyword_metrics
+ result["keywords"].append({
+ "keyword": kw_result.text,
+ "avg_monthly_searches": metrics.avg_monthly_searches,
+ "competition": metrics.competition.name if metrics.competition else "UNSPECIFIED",
+ "competition_index": metrics.competition_index,
+ "low_top_of_page_bid": metrics.low_top_of_page_bid_micros / 1_000_000 if metrics.low_top_of_page_bid_micros else None,
+ "high_top_of_page_bid": metrics.high_top_of_page_bid_micros / 1_000_000 if metrics.high_top_of_page_bid_micros else None,
+ })
+
+ except GoogleAdsException as e:
+ errors = [err.message for err in e.failure.errors]
+ result["error"] = f"Google Ads API error: {'; '.join(errors)}"
+ except Exception as e:
+ result["error"] = f"Keyword volume error: {e}"
+
+ return result
+
+
+def main():
+ parser = argparse.ArgumentParser(
+ description="Google Ads Keyword Planner - SEO keyword research"
+ )
+ parser.add_argument(
+ "command",
+ choices=["ideas", "volume"],
+ help="Command: ideas (keyword suggestions), volume (search volume lookup)",
+ )
+ parser.add_argument("keywords", help="Seed keyword(s), comma-separated for volume")
+ parser.add_argument("--limit", type=int, default=50, help="Max results for ideas (default: 50)")
+ parser.add_argument("--language", default="1000", help="Language ID (default: 1000 = English)")
+ parser.add_argument("--location", default="2840", help="Location ID (default: 2840 = US)")
+ parser.add_argument("--json", "-j", action="store_true", help="Output as JSON")
+
+ args = parser.parse_args()
+
+ if args.command == "ideas":
+ seeds = [k.strip() for k in args.keywords.split(",")]
+ result = generate_keyword_ideas(seeds, language_id=args.language, location_id=args.location, limit=args.limit)
+ elif args.command == "volume":
+ kws = [k.strip() for k in args.keywords.split(",")]
+ result = get_keyword_volumes(kws, language_id=args.language, location_id=args.location)
+
+ if result.get("error"):
+ print(f"Error: {result['error']}", file=sys.stderr)
+ if not args.json:
+ sys.exit(1)
+
+ if args.json:
+ print(json.dumps(result, indent=2, default=str))
+ else:
+ if args.command == "ideas":
+ print(f"=== Keyword Ideas ===")
+ for i, idea in enumerate(result.get("ideas", [])[:20], 1):
+ vol = idea.get("avg_monthly_searches", "?")
+ comp = idea.get("competition", "?")
+ bid_low = idea.get("low_top_of_page_bid")
+ bid_high = idea.get("high_top_of_page_bid")
+ bid_str = f"${bid_low:.2f}-${bid_high:.2f}" if bid_low and bid_high else "N/A"
+ print(f" {i:2d}. {idea['keyword']:40s} | Vol: {vol:>8} | Comp: {comp:8s} | CPC: {bid_str}")
+ elif args.command == "volume":
+ print(f"=== Keyword Volumes ===")
+ for kw in result.get("keywords", []):
+ vol = kw.get("avg_monthly_searches", "?")
+ comp = kw.get("competition", "?")
+ print(f" {kw['keyword']:40s} | Vol: {vol:>8} | Comp: {comp}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/scripts/nlp_analyze.py b/scripts/nlp_analyze.py
new file mode 100644
index 0000000..20756bb
--- /dev/null
+++ b/scripts/nlp_analyze.py
@@ -0,0 +1,309 @@
+#!/usr/bin/env python3
+"""
+Google Cloud Natural Language API - Entity, sentiment, and content analysis.
+
+Enhances E-E-A-T scoring with NLP entity coverage, sentiment analysis,
+and Google's own content classification taxonomy.
+
+Usage:
+ python nlp_analyze.py --text "Your content here" --json
+ python nlp_analyze.py --url https://example.com --json
+ python nlp_analyze.py --text "Your content" --features entities,sentiment,classify
+"""
+
+import argparse
+import json
+import sys
+from typing import Optional
+
+try:
+ import requests
+except ImportError:
+ print("Error: requests library required. Install with: pip install requests", file=sys.stderr)
+ sys.exit(1)
+
+try:
+ from google_auth import get_api_key, validate_url
+except ImportError:
+ import os
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+ from google_auth import get_api_key, validate_url
+
+NLP_ENDPOINT = "https://language.googleapis.com/v2/documents:annotateText"
+
+# Free tier: 5,000 units/month per feature
+# Paid: $0.001 per 1,000-character unit for entity/sentiment
+FEATURES = {
+ "entities": "extractEntities",
+ "sentiment": "extractDocumentSentiment",
+ "classify": "classifyText",
+ "categories": "classifyText",
+ "moderate": "moderateText",
+}
+
+
+def analyze_text(
+ text: str,
+ features: Optional[list] = None,
+ api_key: Optional[str] = None,
+ language: str = "en",
+) -> dict:
+ """
+ Analyze text using Google Cloud Natural Language API.
+
+ Args:
+ text: Text content to analyze (max 1M characters).
+ features: List of features: entities, sentiment, classify, moderate.
+ api_key: Google API key.
+ language: Language code (default: en).
+
+ Returns:
+ Dictionary with entities, sentiment, categories, and moderation results.
+ """
+ result = {
+ "text_length": len(text),
+ "language": language,
+ "entities": [],
+ "sentiment": None,
+ "categories": [],
+ "moderation": [],
+ "error": None,
+ }
+
+ key = api_key or get_api_key()
+ if not key:
+ result["error"] = "No API key. Set GOOGLE_API_KEY or add 'api_key' to config."
+ return result
+
+ if features is None:
+ features = ["entities", "sentiment", "classify"]
+
+ # Build request
+ feature_map = {}
+ for f in features:
+ api_feature = FEATURES.get(f)
+ if api_feature:
+ feature_map[api_feature] = True
+
+ body = {
+ "document": {
+ "type": "PLAIN_TEXT",
+ "content": text[:100000], # API limit
+ "languageCode": language,
+ },
+ "features": feature_map,
+ "encodingType": "UTF8",
+ }
+
+ try:
+ resp = requests.post(
+ f"{NLP_ENDPOINT}?key={key}",
+ json=body,
+ timeout=30,
+ )
+
+ if resp.status_code == 403:
+ result["error"] = (
+ "Cloud Natural Language API access denied. Enable it in "
+ "GCP Console: APIs & Services > Library > Cloud Natural Language API. "
+ "Billing must be enabled on the project."
+ )
+ return result
+
+ if resp.status_code == 429:
+ result["error"] = "NLP API quota exceeded. Free tier: 5,000 units/month."
+ return result
+
+ resp.raise_for_status()
+ data = resp.json()
+ except requests.exceptions.RequestException as e:
+ result["error"] = f"NLP API request failed: {e}"
+ return result
+
+ # Entities
+ for entity in data.get("entities", []):
+ mentions = entity.get("mentions", [])
+ result["entities"].append({
+ "name": entity.get("name", ""),
+ "type": entity.get("type", "UNKNOWN"),
+ "salience": round(entity.get("salience", 0), 4),
+ "sentiment_score": entity.get("sentiment", {}).get("score"),
+ "sentiment_magnitude": entity.get("sentiment", {}).get("magnitude"),
+ "mention_count": len(mentions),
+ "metadata": entity.get("metadata", {}),
+ })
+
+ # Sort by salience (most important first)
+ result["entities"].sort(key=lambda e: e["salience"], reverse=True)
+
+ # Document sentiment
+ doc_sentiment = data.get("documentSentiment", {})
+ if doc_sentiment:
+ score = doc_sentiment.get("score", 0)
+ magnitude = doc_sentiment.get("magnitude", 0)
+ if score > 0.25:
+ tone = "positive"
+ elif score < -0.25:
+ tone = "negative"
+ else:
+ tone = "neutral"
+
+ result["sentiment"] = {
+ "score": round(score, 3),
+ "magnitude": round(magnitude, 3),
+ "tone": tone,
+ "interpretation": (
+ f"{'Positive' if score > 0 else 'Negative' if score < 0 else 'Neutral'} "
+ f"(score: {score:.2f}) with "
+ f"{'high' if magnitude > 2 else 'moderate' if magnitude > 0.5 else 'low'} "
+ f"emotional content (magnitude: {magnitude:.2f})"
+ ),
+ }
+
+ # Sentence-level sentiment
+ sentences = data.get("sentences", [])
+ if sentences:
+ result["sentiment"]["sentence_count"] = len(sentences)
+ sent_scores = [s.get("sentiment", {}).get("score", 0) for s in sentences]
+ result["sentiment"]["most_positive"] = max(sent_scores) if sent_scores else 0
+ result["sentiment"]["most_negative"] = min(sent_scores) if sent_scores else 0
+
+ # Categories (content classification)
+ for cat in data.get("categories", []):
+ result["categories"].append({
+ "name": cat.get("name", ""),
+ "confidence": round(cat.get("confidence", 0), 4),
+ })
+
+ # Moderation categories
+ for mod in data.get("moderationCategories", []):
+ if mod.get("confidence", 0) > 0.5:
+ result["moderation"].append({
+ "name": mod.get("name", ""),
+ "confidence": round(mod.get("confidence", 0), 4),
+ })
+
+ return result
+
+
+def analyze_url(
+ url: str,
+ features: Optional[list] = None,
+ api_key: Optional[str] = None,
+) -> dict:
+ """
+ Fetch a URL's text content and analyze it.
+
+ Args:
+ url: URL to fetch and analyze.
+ features: NLP features to extract.
+ api_key: API key override.
+
+ Returns:
+ Dictionary with NLP analysis results.
+ """
+ if not validate_url(url):
+ return {"error": "Invalid URL. Only http/https URLs to public hosts are accepted."}
+
+ # Fetch the page text
+ try:
+ resp = requests.get(url, timeout=30, headers={
+ "User-Agent": "Mozilla/5.0 (compatible; ClaudeSEO/1.7 NLP Analyzer)"
+ })
+ resp.raise_for_status()
+ html = resp.text
+ except requests.exceptions.RequestException as e:
+ return {"error": f"Could not fetch URL: {e}"}
+
+ # Extract text from HTML (simple approach)
+ try:
+ from bs4 import BeautifulSoup
+ soup = BeautifulSoup(html, "html.parser")
+ # Remove script and style
+ for tag in soup(["script", "style", "nav", "footer", "header"]):
+ tag.decompose()
+ text = soup.get_text(separator=" ", strip=True)
+ except ImportError:
+ # Fallback: regex-based text extraction
+ import re
+ text = re.sub(r"<script[^>]*>.*?</script>", "", html, flags=re.DOTALL | re.IGNORECASE)
+ text = re.sub(r"<style[^>]*>.*?</style>", "", text, flags=re.DOTALL | re.IGNORECASE)
+ text = re.sub(r"<[^>]+>", " ", text)
+ text = re.sub(r"\s+", " ", text).strip()
+
+ if not text or len(text) < 50:
+ return {"error": "Extracted text too short for meaningful NLP analysis."}
+
+ result = analyze_text(text, features=features, api_key=api_key)
+ result["source_url"] = url
+ result["extracted_text_length"] = len(text)
+ return result
+
+
+def main():
+ parser = argparse.ArgumentParser(
+ description="Google Cloud Natural Language API - Entity/sentiment/classification for SEO"
+ )
+ parser.add_argument("--text", "-t", help="Text to analyze")
+ parser.add_argument("--url", "-u", help="URL to fetch and analyze")
+ parser.add_argument(
+ "--features", "-f",
+ default="entities,sentiment,classify",
+ help="Comma-separated features: entities, sentiment, classify, moderate (default: entities,sentiment,classify)",
+ )
+ parser.add_argument("--api-key", help="API key override")
+ parser.add_argument("--json", "-j", action="store_true", help="Output as JSON")
+
+ args = parser.parse_args()
+
+ if not args.text and not args.url:
+ print("Error: Provide --text or --url to analyze.", file=sys.stderr)
+ sys.exit(1)
+
+ features = [f.strip() for f in args.features.split(",")]
+
+ if args.url:
+ result = analyze_url(args.url, features=features, api_key=args.api_key)
+ else:
+ result = analyze_text(args.text, features=features, api_key=args.api_key)
+
+ if result.get("error"):
+ print(f"Error: {result['error']}", file=sys.stderr)
+ if not args.json:
+ sys.exit(1)
+
+ if args.json:
+ print(json.dumps(result, indent=2))
+ else:
+ if result.get("source_url"):
+ print(f"=== NLP Analysis: {result['source_url']} ===")
+ print(f"Text extracted: {result.get('extracted_text_length', 0):,} chars")
+ else:
+ print(f"=== NLP Analysis ({result.get('text_length', 0):,} chars) ===")
+
+ sent = result.get("sentiment")
+ if sent:
+ print(f"\nSentiment: {sent['tone'].upper()} (score: {sent['score']}, magnitude: {sent['magnitude']})")
+ print(f" {sent['interpretation']}")
+
+ entities = result.get("entities", [])
+ if entities:
+ print(f"\nTop Entities ({len(entities)} total):")
+ for e in entities[:15]:
+ print(f" [{e['type']:12s}] {e['name']} (salience: {e['salience']:.3f})")
+
+ categories = result.get("categories", [])
+ if categories:
+ print(f"\nContent Categories:")
+ for c in categories:
+ print(f" {c['name']} ({c['confidence']:.1%})")
+
+ moderation = result.get("moderation", [])
+ if moderation:
+ print(f"\nModeration Flags:")
+ for m in moderation:
+ print(f" {m['name']} ({m['confidence']:.1%})")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/scripts/pagespeed_check.py b/scripts/pagespeed_check.py
new file mode 100644
index 0000000..166c58d
--- /dev/null
+++ b/scripts/pagespeed_check.py
@@ -0,0 +1,649 @@
+#!/usr/bin/env python3
+"""
+PageSpeed Insights v5 + CrUX API combined checker.
+
+Runs Lighthouse lab analysis via PSI and fetches real Chrome UX field data
+via the CrUX API. Merges both perspectives into a single report.
+
+Usage:
+ python pagespeed_check.py https://example.com
+ python pagespeed_check.py https://example.com --strategy mobile
+ python pagespeed_check.py https://example.com --crux-only
+ python pagespeed_check.py https://example.com --psi-only --json
+"""
+
+import argparse
+import json
+import sys
+from typing import Optional
+from urllib.parse import urlparse
+
+try:
+ import requests
+except ImportError:
+ print("Error: requests library required. Install with: pip install requests")
+ sys.exit(1)
+
+# Import credential helper (same directory)
+try:
+ from google_auth import get_api_key, load_config, validate_url
+except ImportError:
+ # Fallback: try relative import from scripts/
+ import os
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+ from google_auth import get_api_key, load_config, validate_url
+
+PSI_ENDPOINT = "https://www.googleapis.com/pagespeedonline/v5/runPagespeed"
+CRUX_ENDPOINT = "https://chromeuxreport.googleapis.com/v1/records:queryRecord"
+
+# Core Web Vitals thresholds (March 2026)
+CWV_THRESHOLDS = {
+ "largest_contentful_paint": {"good": 2500, "poor": 4000, "unit": "ms", "label": "LCP"},
+ "interaction_to_next_paint": {"good": 200, "poor": 500, "unit": "ms", "label": "INP"},
+ "cumulative_layout_shift": {"good": 0.1, "poor": 0.25, "unit": "", "label": "CLS"},
+ "first_contentful_paint": {"good": 1800, "poor": 3000, "unit": "ms", "label": "FCP"},
+ "experimental_time_to_first_byte": {"good": 800, "poor": 1800, "unit": "ms", "label": "TTFB"},
+}
+
+PSI_METRIC_MAP = {
+ "LARGEST_CONTENTFUL_PAINT_MS": "largest_contentful_paint",
+ "INTERACTION_TO_NEXT_PAINT": "interaction_to_next_paint",
+ "CUMULATIVE_LAYOUT_SHIFT_SCORE": "cumulative_layout_shift",
+ "FIRST_CONTENTFUL_PAINT_MS": "first_contentful_paint",
+ "EXPERIMENTAL_TIME_TO_FIRST_BYTE": "experimental_time_to_first_byte",
+}
+
+
+def rate_metric(metric_name: str, value: float) -> str:
+ """Rate a CWV metric as good/needs-improvement/poor."""
+ thresholds = CWV_THRESHOLDS.get(metric_name)
+ if not thresholds:
+ return "unknown"
+ if value <= thresholds["good"]:
+ return "good"
+ elif value <= thresholds["poor"]:
+ return "needs-improvement"
+ else:
+ return "poor"
+
+
+def run_pagespeed(
+ url: str,
+ strategy: str = "mobile",
+ api_key: Optional[str] = None,
+ categories: Optional[list] = None,
+) -> dict:
+ """
+ Run PageSpeed Insights v5 analysis.
+
+ Args:
+ url: URL to analyze.
+ strategy: 'mobile' or 'desktop'.
+ api_key: Google API key (optional but recommended for quota).
+ categories: List of categories: PERFORMANCE, ACCESSIBILITY, BEST_PRACTICES, SEO.
+
+ Returns:
+ Dictionary with lighthouse scores, lab metrics, field data (if available),
+ and opportunities. Error in 'error' field on failure.
+ """
+ result = {
+ "url": url,
+ "strategy": strategy,
+ "lighthouse_scores": {},
+ "lab_metrics": {},
+ "field_metrics": {},
+ "opportunities": [],
+ "diagnostics": [],
+ "failed_audits": [],
+ "passed_audits_count": 0,
+ "seo_audits": [],
+ "accessibility_audits": [],
+ "analysis_timestamp": None,
+ "error": None,
+ }
+
+ if not validate_url(url):
+ result["error"] = "Invalid URL. Only http/https URLs to public hosts are accepted."
+ return result
+
+ if categories is None:
+ categories = ["PERFORMANCE", "ACCESSIBILITY", "BEST_PRACTICES", "SEO"]
+
+ params = {
+ "url": url,
+ "strategy": strategy.upper(),
+ }
+ for cat in categories:
+ params.setdefault("category", [])
+ if isinstance(params["category"], list):
+ params["category"].append(cat)
+
+ if api_key:
+ params["key"] = api_key
+
+ try:
+ resp = requests.get(PSI_ENDPOINT, params=params, timeout=120)
+ resp.raise_for_status()
+ data = resp.json()
+ except requests.exceptions.Timeout:
+ result["error"] = "PageSpeed Insights request timed out (120s). The target page may be very slow."
+ return result
+ except requests.exceptions.HTTPError as e:
+ if resp.status_code == 429:
+ result["error"] = "PSI rate limit exceeded (240 QPM / 25,000 QPD). Wait and retry."
+ elif resp.status_code == 400:
+ result["error"] = f"Invalid URL or parameters: {resp.text}"
+ else:
+ result["error"] = f"PSI API error {resp.status_code}: {e}"
+ return result
+ except requests.exceptions.RequestException as e:
+ result["error"] = f"Request failed: {e}"
+ return result
+
+ result["analysis_timestamp"] = data.get("analysisUTCTimestamp")
+
+ # Lighthouse scores
+ lr = data.get("lighthouseResult", {})
+ for cat_key, cat_data in lr.get("categories", {}).items():
+ result["lighthouse_scores"][cat_key] = round(cat_data.get("score", 0) * 100)
+
+ # Lab metrics from Lighthouse audits
+ audits = lr.get("audits", {})
+ lab_audit_ids = [
+ "first-contentful-paint", "largest-contentful-paint",
+ "total-blocking-time", "cumulative-layout-shift",
+ "speed-index", "interactive",
+ ]
+ for audit_id in lab_audit_ids:
+ audit = audits.get(audit_id, {})
+ if audit.get("numericValue") is not None:
+ result["lab_metrics"][audit_id] = {
+ "value": audit["numericValue"],
+ "display": audit.get("displayValue", ""),
+ "score": audit.get("score"),
+ }
+
+ # Field data from PSI (loading experience)
+ for exp_key in ["loadingExperience", "originLoadingExperience"]:
+ exp = data.get(exp_key, {})
+ metrics = exp.get("metrics", {})
+ if metrics:
+ field_source = "url" if exp_key == "loadingExperience" else "origin"
+ for psi_name, crux_name in PSI_METRIC_MAP.items():
+ metric_data = metrics.get(psi_name, {})
+ if metric_data:
+ p75 = metric_data.get("percentile")
+ category = metric_data.get("category", "NONE")
+ if p75 is not None:
+ # CLS from PSI is already numeric
+ if crux_name == "cumulative_layout_shift":
+ p75_val = p75 / 100 if p75 > 1 else p75
+ else:
+ p75_val = p75
+ result["field_metrics"][f"{field_source}_{crux_name}"] = {
+ "p75": p75_val,
+ "rating": category.lower().replace("_", "-"),
+ "source": f"PSI {field_source}-level",
+ }
+
+ # Opportunities
+ for audit_id, audit in audits.items():
+ if audit.get("details", {}).get("type") == "opportunity":
+ savings = audit.get("details", {}).get("overallSavingsMs")
+ if savings and savings > 0:
+ result["opportunities"].append({
+ "id": audit_id,
+ "title": audit.get("title", audit_id),
+ "savings_ms": savings,
+ "description": audit.get("description", ""),
+ })
+
+ result["opportunities"].sort(key=lambda x: x["savings_ms"], reverse=True)
+
+ # Diagnostics (performance bottlenecks)
+ diagnostic_ids = [
+ "dom-size", "render-blocking-resources", "uses-long-cache-ttl",
+ "total-byte-weight", "mainthread-work-breakdown", "bootup-time",
+ "font-display", "third-party-summary", "largest-contentful-paint-element",
+ "layout-shifts", "long-tasks", "duplicated-javascript",
+ "legacy-javascript", "unused-javascript", "unused-css-rules",
+ ]
+ for diag_id in diagnostic_ids:
+ audit = audits.get(diag_id, {})
+ if audit:
+ score = audit.get("score")
+ result["diagnostics"].append({
+ "id": diag_id,
+ "title": audit.get("title", diag_id),
+ "display": audit.get("displayValue", ""),
+ "score": score,
+ "description": audit.get("description", ""),
+ })
+
+ # Failed and warning audits (score < 0.9, excluding opportunities already captured)
+ opportunity_ids = {o["id"] for o in result["opportunities"]}
+ passed_count = 0
+ for audit_id, audit in audits.items():
+ score = audit.get("score")
+ if score is None:
+ continue
+ if score >= 0.9:
+ passed_count += 1
+ continue
+ if audit_id in opportunity_ids:
+ continue
+ result["failed_audits"].append({
+ "id": audit_id,
+ "title": audit.get("title", audit_id),
+ "score": score,
+ "display": audit.get("displayValue", ""),
+ "description": audit.get("description", ""),
+ })
+ result["passed_audits_count"] = passed_count
+ result["failed_audits"].sort(key=lambda x: x.get("score", 1))
+
+ # SEO audits from the SEO category
+ seo_cat = lr.get("categories", {}).get("seo", {})
+ for ref in seo_cat.get("auditRefs", []):
+ audit = audits.get(ref.get("id"), {})
+ if audit and audit.get("score") is not None:
+ result["seo_audits"].append({
+ "id": ref["id"],
+ "title": audit.get("title", ref["id"]),
+ "score": audit["score"],
+ "pass": audit["score"] >= 0.9,
+ })
+
+ # Accessibility audits from the accessibility category
+ a11y_cat = lr.get("categories", {}).get("accessibility", {})
+ for ref in a11y_cat.get("auditRefs", []):
+ audit = audits.get(ref.get("id"), {})
+ if audit and audit.get("score") is not None and audit["score"] < 0.9:
+ result["accessibility_audits"].append({
+ "id": ref["id"],
+ "title": audit.get("title", ref["id"]),
+ "score": audit["score"],
+ "display": audit.get("displayValue", ""),
+ })
+
+ # Audit details: extract top items from audits with details.items[]
+ # This captures WHICH specific resources are problems (e.g., "hero.jpg is 2MB")
+ for audit_id, audit in audits.items():
+ details = audit.get("details", {})
+ items = details.get("items", [])
+ headings = details.get("headings", [])
+ if items and headings:
+ heading_keys = [h.get("key", "") for h in headings if h.get("key")]
+ extracted_items = []
+ for item in items[:5]:
+ row = {}
+ for key in heading_keys:
+ val = item.get(key)
+ if isinstance(val, dict):
+ row[key] = val.get("url") or val.get("text") or str(val)[:200]
+ elif val is not None:
+ row[key] = val
+ if row:
+ extracted_items.append(row)
+ if extracted_items:
+ result["audit_details"][audit_id] = {
+ "title": audit.get("title", audit_id),
+ "headings": heading_keys,
+ "items": extracted_items,
+ "total_items": len(items),
+ }
+
+ return result
+
+
+def query_crux(
+ url_or_origin: str,
+ api_key: str,
+ form_factor: Optional[str] = None,
+) -> dict:
+ """
+ Query the CrUX API for field data (28-day rolling average).
+
+ Args:
+ url_or_origin: Full URL or origin (e.g., https://example.com).
+ api_key: Google API key.
+ form_factor: DESKTOP, PHONE, or TABLET. None for all form factors.
+
+ Returns:
+ Dictionary with p75 metrics, distributions, collection period, and rating.
+ Error in 'error' field on failure.
+ """
+ result = {
+ "target": url_or_origin,
+ "metrics": {},
+ "collection_period": None,
+ "form_factor": form_factor or "ALL",
+ "error": None,
+ }
+
+ if not validate_url(url_or_origin):
+ result["error"] = "Invalid URL. Only http/https URLs to public hosts are accepted."
+ return result
+
+ parsed = urlparse(url_or_origin)
+ # Determine if this is a URL or an origin
+ is_origin = parsed.path in ("", "/") and not parsed.query
+
+ body = {}
+ if is_origin:
+ body["origin"] = f"{parsed.scheme}://{parsed.netloc}"
+ else:
+ body["url"] = url_or_origin
+
+ if form_factor:
+ body["formFactor"] = form_factor.upper()
+
+ try:
+ resp = requests.post(
+ f"{CRUX_ENDPOINT}?key={api_key}",
+ json=body,
+ timeout=30,
+ )
+
+ if resp.status_code == 404:
+ target_type = "origin" if is_origin else "URL"
+ result["error"] = (
+ f"No CrUX data for this {target_type}. "
+ "The site likely has insufficient Chrome traffic volume for eligibility."
+ )
+ return result
+
+ if resp.status_code == 429:
+ result["error"] = "CrUX API rate limit exceeded (150 QPM shared with History API). Wait and retry."
+ return result
+
+ resp.raise_for_status()
+ data = resp.json()
+ except requests.exceptions.RequestException as e:
+ result["error"] = f"CrUX API request failed: {e}"
+ return result
+
+ record = data.get("record", {})
+
+ # Collection period
+ cp = record.get("collectionPeriod", {})
+ if cp:
+ first = cp.get("firstDate", {})
+ last = cp.get("lastDate", {})
+ result["collection_period"] = {
+ "first": f"{first.get('year')}-{first.get('month', 0):02d}-{first.get('day', 0):02d}",
+ "last": f"{last.get('year')}-{last.get('month', 0):02d}-{last.get('day', 0):02d}",
+ }
+
+ # Metrics
+ for metric_name, metric_data in record.get("metrics", {}).items():
+ p75s = metric_data.get("percentiles", {})
+ p75 = p75s.get("p75")
+ if p75 is None:
+ continue
+
+ # CLS is string-encoded in CrUX -- parse carefully
+ if metric_name == "cumulative_layout_shift":
+ try:
+ p75_val = float(str(p75))
+ except (ValueError, TypeError):
+ p75_val = 0.0
+ else:
+ try:
+ p75_val = int(p75)
+ except (ValueError, TypeError):
+ try:
+ p75_val = float(p75)
+ except (ValueError, TypeError):
+ continue
+
+ rating = rate_metric(metric_name, p75_val)
+ thresholds = CWV_THRESHOLDS.get(metric_name, {})
+
+ result["metrics"][metric_name] = {
+ "p75": p75_val,
+ "rating": rating,
+ "label": thresholds.get("label", metric_name),
+ "unit": thresholds.get("unit", ""),
+ "good_threshold": thresholds.get("good"),
+ "poor_threshold": thresholds.get("poor"),
+ }
+
+ # Distributions
+ histogram = metric_data.get("histogram", [])
+ if histogram:
+ densities = [bin_data.get("density", 0) for bin_data in histogram]
+ if len(densities) >= 3:
+ result["metrics"][metric_name]["distribution"] = {
+ "good": round(densities[0] * 100, 1),
+ "needs_improvement": round(densities[1] * 100, 1),
+ "poor": round(densities[2] * 100, 1),
+ }
+
+ return result
+
+
+def combined_check(
+ url: str,
+ api_key: Optional[str] = None,
+ strategy: str = "both",
+) -> dict:
+ """
+ Run combined PSI + CrUX check.
+
+ Args:
+ url: URL to analyze.
+ api_key: Google API key.
+ strategy: 'mobile', 'desktop', or 'both'.
+
+ Returns:
+ Dictionary with PSI results (per strategy) and CrUX field data.
+ """
+ result = {
+ "url": url,
+ "psi": {},
+ "crux": None,
+ "error": None,
+ }
+
+ strategies = ["mobile", "desktop"] if strategy == "both" else [strategy]
+
+ for strat in strategies:
+ psi_result = run_pagespeed(url, strategy=strat, api_key=api_key)
+ result["psi"][strat] = psi_result
+ if psi_result.get("error"):
+ result["error"] = psi_result["error"]
+
+ # CrUX (separate call for accurate field data)
+ if api_key:
+ crux_result = query_crux(url, api_key)
+ result["crux"] = crux_result
+ # Also try origin-level if URL-level has no data
+ if crux_result.get("error") and "insufficient" in crux_result.get("error", ""):
+ parsed = urlparse(url)
+ origin = f"{parsed.scheme}://{parsed.netloc}"
+ origin_result = query_crux(origin, api_key)
+ if not origin_result.get("error"):
+ result["crux"] = origin_result
+ result["crux"]["note"] = "URL-level data unavailable; showing origin-level data"
+
+ return result
+
+
+def main():
+ parser = argparse.ArgumentParser(
+ description="PageSpeed Insights v5 + CrUX API combined checker"
+ )
+ parser.add_argument("url", help="URL to analyze")
+ parser.add_argument(
+ "--strategy", "-s",
+ choices=["mobile", "desktop", "both"],
+ default="both",
+ help="Analysis strategy (default: both)",
+ )
+ parser.add_argument(
+ "--api-key",
+ help="Google API key (overrides config/env)",
+ )
+ parser.add_argument(
+ "--crux-only",
+ action="store_true",
+ help="Only fetch CrUX field data (skip PSI Lighthouse)",
+ )
+ parser.add_argument(
+ "--psi-only",
+ action="store_true",
+ help="Only run PSI Lighthouse (skip CrUX API)",
+ )
+ parser.add_argument(
+ "--form-factor",
+ choices=["PHONE", "DESKTOP", "TABLET"],
+ help="CrUX form factor filter",
+ )
+ parser.add_argument(
+ "--json", "-j",
+ action="store_true",
+ help="Output as JSON",
+ )
+
+ args = parser.parse_args()
+
+ api_key = args.api_key or get_api_key()
+
+ if args.crux_only:
+ if not api_key:
+ print("Error: CrUX API requires an API key. Use --api-key or configure GOOGLE_API_KEY.", file=sys.stderr)
+ sys.exit(1)
+ result = query_crux(args.url, api_key, form_factor=args.form_factor)
+ elif args.psi_only:
+ strategies = ["mobile", "desktop"] if args.strategy == "both" else [args.strategy]
+ result = {"psi": {}}
+ for strat in strategies:
+ result["psi"][strat] = run_pagespeed(args.url, strategy=strat, api_key=api_key)
+ else:
+ result = combined_check(args.url, api_key=api_key, strategy=args.strategy)
+
+ if args.json:
+ print(json.dumps(result, indent=2))
+ else:
+ # Pretty print summary
+ if args.crux_only:
+ _print_crux_summary(result)
+ elif args.psi_only:
+ for strat, psi in result.get("psi", {}).items():
+ _print_psi_summary(psi)
+ else:
+ for strat, psi in result.get("psi", {}).items():
+ _print_psi_summary(psi)
+ if result.get("crux"):
+ print()
+ _print_crux_summary(result["crux"])
+
+ # Exit with error code if any errors occurred
+ if isinstance(result, dict) and result.get("error"):
+ sys.exit(1)
+
+
+def _print_psi_summary(psi: dict):
+ """Print PSI results in human-readable format."""
+ if psi.get("error"):
+ print(f"PSI Error ({psi.get('strategy', '?')}): {psi['error']}")
+ return
+
+ print(f"\n=== PageSpeed Insights ({psi.get('strategy', 'unknown')}) ===")
+ print(f"URL: {psi.get('url')}")
+ print(f"Timestamp: {psi.get('analysis_timestamp', 'N/A')}")
+
+ scores = psi.get("lighthouse_scores", {})
+ if scores:
+ print("\nLighthouse Scores:")
+ for cat, score in scores.items():
+ print(f" {cat}: {score}/100")
+
+ lab = psi.get("lab_metrics", {})
+ if lab:
+ print("\nLab Metrics:")
+ for metric_id, data in lab.items():
+ print(f" {metric_id}: {data.get('display', data.get('value'))}")
+
+ opps = psi.get("opportunities", [])
+ if opps:
+ print("\nTop Opportunities:")
+ for opp in opps[:5]:
+ print(f" - {opp['title']} (save ~{opp['savings_ms']}ms)")
+
+ failed = psi.get("failed_audits", [])
+ if failed:
+ print(f"\nFailed/Warning Audits ({len(failed)}):")
+ for a in failed[:10]:
+ score_pct = f"{a['score']:.0%}" if a['score'] is not None else "?"
+ print(f" [{score_pct}] {a['title']} {a.get('display', '')}")
+
+ diags = psi.get("diagnostics", [])
+ notable_diags = [d for d in diags if d.get("score") is not None and d["score"] < 0.9]
+ if notable_diags:
+ print(f"\nDiagnostics (needs attention):")
+ for d in notable_diags[:5]:
+ score_pct = f"{d['score']:.0%}" if d['score'] is not None else "info"
+ print(f" [{score_pct}] {d['title']}: {d.get('display', '')}")
+
+ seo = psi.get("seo_audits", [])
+ seo_failed = [a for a in seo if not a.get("pass")]
+ if seo_failed:
+ print(f"\nSEO Issues ({len(seo_failed)}):")
+ for a in seo_failed:
+ print(f" [FAIL] {a['title']}")
+ elif seo:
+ print(f"\nSEO: All {len(seo)} checks passed")
+
+ a11y = psi.get("accessibility_audits", [])
+ if a11y:
+ print(f"\nAccessibility Issues ({len(a11y)}):")
+ for a in a11y[:5]:
+ print(f" [{a['score']:.0%}] {a['title']}")
+
+ passed = psi.get("passed_audits_count", 0)
+ if passed:
+ print(f"\nPassed: {passed} audits")
+
+
+def _print_crux_summary(crux: dict):
+ """Print CrUX results in human-readable format."""
+ if crux.get("error"):
+ print(f"CrUX Error: {crux['error']}")
+ return
+
+ print(f"=== CrUX Field Data ({crux.get('form_factor', 'ALL')}) ===")
+ print(f"Target: {crux.get('target')}")
+
+ if crux.get("note"):
+ print(f"Note: {crux['note']}")
+
+ cp = crux.get("collection_period", {})
+ if cp:
+ print(f"Period: {cp.get('first')} to {cp.get('last')}")
+
+ metrics = crux.get("metrics", {})
+ if metrics:
+ print("\nCore Web Vitals (p75):")
+ for name, data in metrics.items():
+ label = data.get("label", name)
+ p75 = data.get("p75")
+ unit = data.get("unit", "")
+ rating = data.get("rating", "?")
+ good = data.get("good_threshold")
+
+ rating_icon = {"good": "GOOD", "needs-improvement": "NEEDS IMPROVEMENT", "poor": "POOR"}.get(rating, "?")
+
+ if name == "cumulative_layout_shift":
+ print(f" {label}: {p75:.3f} [{rating_icon}] (threshold: <={good})")
+ else:
+ print(f" {label}: {p75}{unit} [{rating_icon}] (threshold: <={good}{unit})")
+
+ dist = data.get("distribution")
+ if dist:
+ print(f" Good: {dist['good']}% | NI: {dist['needs_improvement']}% | Poor: {dist['poor']}%")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/scripts/youtube_search.py b/scripts/youtube_search.py
new file mode 100644
index 0000000..11b8815
--- /dev/null
+++ b/scripts/youtube_search.py
@@ -0,0 +1,355 @@
+#!/usr/bin/env python3
+"""
+YouTube Data API v3 - Search, video details, and channel data for SEO.
+
+YouTube mentions have the strongest AI visibility correlation (0.737).
+This script provides authoritative YouTube data directly from Google.
+
+Usage:
+ python youtube_search.py search "claude code seo"
+ python youtube_search.py video dQw4w9WgXcQ --json
+ python youtube_search.py channel UCxxxxxx --json
+"""
+
+import argparse
+import json
+import sys
+from typing import Optional
+
+try:
+ from googleapiclient.discovery import build
+except ImportError:
+ print(
+ "Error: google-api-python-client required. "
+ "Install with: pip install google-api-python-client",
+ file=sys.stderr,
+ )
+ sys.exit(1)
+
+try:
+ from google_auth import get_api_key
+except ImportError:
+ import os
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+ from google_auth import get_api_key
+
+# YouTube Data API v3 quota costs:
+# search.list = 100 units, videos.list = 1 unit, channels.list = 1 unit
+# Default quota: 10,000 units/day = ~100 searches or ~10,000 video lookups
+YOUTUBE_API_SERVICE = "youtube"
+YOUTUBE_API_VERSION = "v3"
+
+
+def _build_youtube_service(api_key: Optional[str] = None):
+ """Build the YouTube Data API v3 service."""
+ key = api_key or get_api_key()
+ if not key:
+ return None
+ try:
+ return build(YOUTUBE_API_SERVICE, YOUTUBE_API_VERSION, developerKey=key)
+ except Exception as e:
+ print(f"Error building YouTube service: {e}", file=sys.stderr)
+ return None
+
+
+def search_videos(
+ query: str,
+ max_results: int = 10,
+ order: str = "relevance",
+ api_key: Optional[str] = None,
+) -> dict:
+ """
+ Search YouTube for videos matching a query.
+
+ Args:
+ query: Search query string.
+ max_results: Max results (1-50, default 10).
+ order: Sort order: relevance, date, rating, viewCount, title.
+ api_key: Optional API key override.
+
+ Returns:
+ Dictionary with videos list and metadata.
+ """
+ result = {"query": query, "videos": [], "total_results": 0, "error": None}
+
+ service = _build_youtube_service(api_key)
+ if not service:
+ result["error"] = "No API key. Set GOOGLE_API_KEY or add 'api_key' to config."
+ return result
+
+ try:
+ response = service.search().list(
+ q=query,
+ part="snippet",
+ type="video",
+ maxResults=min(max_results, 50),
+ order=order,
+ ).execute()
+
+ result["total_results"] = response.get("pageInfo", {}).get("totalResults", 0)
+
+ # Get video IDs for statistics
+ video_ids = []
+ snippets = {}
+ for item in response.get("items", []):
+ vid = item["id"].get("videoId")
+ if vid:
+ video_ids.append(vid)
+ snippets[vid] = item.get("snippet", {})
+
+ # Fetch statistics for all videos in one call (1 unit)
+ if video_ids:
+ stats_response = service.videos().list(
+ id=",".join(video_ids),
+ part="statistics,contentDetails",
+ ).execute()
+
+ stats_map = {}
+ for item in stats_response.get("items", []):
+ stats_map[item["id"]] = {
+ "views": int(item.get("statistics", {}).get("viewCount", 0)),
+ "likes": int(item.get("statistics", {}).get("likeCount", 0)),
+ "comments": int(item.get("statistics", {}).get("commentCount", 0)),
+ "duration": item.get("contentDetails", {}).get("duration", ""),
+ }
+
+ for vid in video_ids:
+ snip = snippets.get(vid, {})
+ stats = stats_map.get(vid, {})
+ result["videos"].append({
+ "video_id": vid,
+ "title": snip.get("title", ""),
+ "channel": snip.get("channelTitle", ""),
+ "channel_id": snip.get("channelId", ""),
+ "published": snip.get("publishedAt", ""),
+ "description": snip.get("description", "")[:300],
+ "thumbnail": snip.get("thumbnails", {}).get("high", {}).get("url", ""),
+ "views": stats.get("views", 0),
+ "likes": stats.get("likes", 0),
+ "comments": stats.get("comments", 0),
+ "duration": stats.get("duration", ""),
+ "url": f"https://www.youtube.com/watch?v={vid}",
+ })
+
+ except Exception as e:
+ error_str = str(e)
+ if "403" in error_str:
+ result["error"] = (
+ "YouTube Data API access denied. Ensure the API is enabled "
+ "in your GCP project (APIs & Services > Library > YouTube Data API v3)."
+ )
+ elif "429" in error_str:
+ result["error"] = "YouTube API quota exceeded (10,000 units/day). Search costs 100 units."
+ else:
+ result["error"] = f"YouTube API error: {e}"
+
+ return result
+
+
+def get_video_details(
+ video_id: str,
+ api_key: Optional[str] = None,
+) -> dict:
+ """
+ Get detailed information about a specific YouTube video.
+
+ Args:
+ video_id: YouTube video ID.
+ api_key: Optional API key override.
+
+ Returns:
+ Dictionary with video details, statistics, and top comments.
+ """
+ result = {"video_id": video_id, "details": None, "comments": [], "error": None}
+
+ service = _build_youtube_service(api_key)
+ if not service:
+ result["error"] = "No API key configured."
+ return result
+
+ try:
+ # Video details (1 unit)
+ response = service.videos().list(
+ id=video_id,
+ part="snippet,statistics,contentDetails,topicDetails",
+ ).execute()
+
+ items = response.get("items", [])
+ if not items:
+ result["error"] = f"Video not found: {video_id}"
+ return result
+
+ item = items[0]
+ snip = item.get("snippet", {})
+ stats = item.get("statistics", {})
+ content = item.get("contentDetails", {})
+ topics = item.get("topicDetails", {})
+
+ result["details"] = {
+ "title": snip.get("title", ""),
+ "channel": snip.get("channelTitle", ""),
+ "channel_id": snip.get("channelId", ""),
+ "published": snip.get("publishedAt", ""),
+ "description": snip.get("description", ""),
+ "tags": snip.get("tags", []),
+ "category_id": snip.get("categoryId", ""),
+ "duration": content.get("duration", ""),
+ "definition": content.get("definition", ""),
+ "caption": content.get("caption", "false"),
+ "views": int(stats.get("viewCount", 0)),
+ "likes": int(stats.get("likeCount", 0)),
+ "comments_count": int(stats.get("commentCount", 0)),
+ "favorites": int(stats.get("favoriteCount", 0)),
+ "topic_categories": topics.get("topicCategories", []),
+ "url": f"https://www.youtube.com/watch?v={video_id}",
+ }
+
+ # Top comments (1 unit)
+ try:
+ comments_response = service.commentThreads().list(
+ videoId=video_id,
+ part="snippet",
+ maxResults=10,
+ order="relevance",
+ textFormat="plainText",
+ ).execute()
+
+ for thread in comments_response.get("items", []):
+ comment = thread.get("snippet", {}).get("topLevelComment", {}).get("snippet", {})
+ result["comments"].append({
+ "author": comment.get("authorDisplayName", ""),
+ "text": comment.get("textDisplay", "")[:500],
+ "likes": comment.get("likeCount", 0),
+ "published": comment.get("publishedAt", ""),
+ })
+ except Exception:
+ pass # Comments may be disabled
+
+ except Exception as e:
+ result["error"] = f"YouTube API error: {e}"
+
+ return result
+
+
+def get_channel_info(
+ channel_id: str,
+ api_key: Optional[str] = None,
+) -> dict:
+ """
+ Get channel information.
+
+ Args:
+ channel_id: YouTube channel ID.
+ api_key: Optional API key override.
+
+ Returns:
+ Dictionary with channel details.
+ """
+ result = {"channel_id": channel_id, "channel": None, "error": None}
+
+ service = _build_youtube_service(api_key)
+ if not service:
+ result["error"] = "No API key configured."
+ return result
+
+ try:
+ response = service.channels().list(
+ id=channel_id,
+ part="snippet,statistics,brandingSettings",
+ ).execute()
+
+ items = response.get("items", [])
+ if not items:
+ result["error"] = f"Channel not found: {channel_id}"
+ return result
+
+ item = items[0]
+ snip = item.get("snippet", {})
+ stats = item.get("statistics", {})
+
+ result["channel"] = {
+ "title": snip.get("title", ""),
+ "description": snip.get("description", "")[:500],
+ "custom_url": snip.get("customUrl", ""),
+ "published": snip.get("publishedAt", ""),
+ "country": snip.get("country", ""),
+ "subscribers": int(stats.get("subscriberCount", 0)),
+ "videos": int(stats.get("videoCount", 0)),
+ "views": int(stats.get("viewCount", 0)),
+ "thumbnail": snip.get("thumbnails", {}).get("high", {}).get("url", ""),
+ }
+
+ except Exception as e:
+ result["error"] = f"YouTube API error: {e}"
+
+ return result
+
+
+def main():
+ parser = argparse.ArgumentParser(
+ description="YouTube Data API v3 - Search and video analysis for SEO"
+ )
+ parser.add_argument(
+ "command",
+ choices=["search", "video", "channel"],
+ help="Command: search, video (details), channel (info)",
+ )
+ parser.add_argument("query", help="Search query, video ID, or channel ID")
+ parser.add_argument("--limit", type=int, default=10, help="Max results for search (default: 10)")
+ parser.add_argument(
+ "--order",
+ choices=["relevance", "date", "rating", "viewCount", "title"],
+ default="relevance",
+ help="Sort order for search (default: relevance)",
+ )
+ parser.add_argument("--api-key", help="API key override")
+ parser.add_argument("--json", "-j", action="store_true", help="Output as JSON")
+
+ args = parser.parse_args()
+
+ if args.command == "search":
+ result = search_videos(args.query, max_results=args.limit, order=args.order, api_key=args.api_key)
+ elif args.command == "video":
+ result = get_video_details(args.query, api_key=args.api_key)
+ elif args.command == "channel":
+ result = get_channel_info(args.query, api_key=args.api_key)
+
+ if result.get("error"):
+ print(f"Error: {result['error']}", file=sys.stderr)
+ if not args.json:
+ sys.exit(1)
+
+ if args.json:
+ print(json.dumps(result, indent=2))
+ else:
+ if args.command == "search":
+ print(f"=== YouTube Search: {args.query} ===")
+ print(f"Results: {result.get('total_results', 0):,}")
+ for i, v in enumerate(result.get("videos", []), 1):
+ print(f"\n {i}. {v['title']}")
+ print(f" {v['channel']} | {v['views']:,} views | {v['likes']:,} likes | {v['duration']}")
+ print(f" {v['url']}")
+ elif args.command == "video":
+ d = result.get("details", {})
+ if d:
+ print(f"=== {d.get('title')} ===")
+ print(f"Channel: {d.get('channel')}")
+ print(f"Views: {d.get('views', 0):,} | Likes: {d.get('likes', 0):,} | Comments: {d.get('comments_count', 0):,}")
+ print(f"Published: {d.get('published', '')[:10]} | Duration: {d.get('duration')}")
+ tags = d.get("tags", [])
+ if tags:
+ print(f"Tags: {', '.join(tags[:10])}")
+ comments = result.get("comments", [])
+ if comments:
+ print(f"\nTop Comments ({len(comments)}):")
+ for c in comments[:5]:
+ print(f" [{c['likes']} likes] {c['author']}: {c['text'][:100]}")
+ elif args.command == "channel":
+ ch = result.get("channel", {})
+ if ch:
+ print(f"=== {ch.get('title')} ===")
+ print(f"Subscribers: {ch.get('subscribers', 0):,} | Videos: {ch.get('videos', 0):,} | Views: {ch.get('views', 0):,}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/skills/seo-audit/SKILL.md b/skills/seo-audit/SKILL.md
index 92098c0..481e756 100644
--- a/skills/seo-audit/SKILL.md
+++ b/skills/seo-audit/SKILL.md
@@ -2,8 +2,8 @@
name: seo-audit
description: >
Full website SEO audit with parallel subagent delegation. Crawls up to 500
- pages, detects business type, delegates to 9 specialists (7 core + 2
- conditional local), generates health score. Use when user says "audit",
+ pages, detects business type, delegates to 10 specialists (7 core + 3
+ conditional), generates health score. Use when user says "audit",
"full SEO check", "analyze my site", or "website health check".
user-invokable: true
argument-hint: "[url]"
@@ -11,7 +11,7 @@ license: MIT
allowed-tools: Read, Grep, Glob, Bash, WebFetch, Agent
metadata:
author: AgriciDaniel
- version: "1.6.1"
+ version: "1.7.0"
category: seo
---
@@ -32,6 +32,7 @@ metadata:
- `seo-geo` -- AI crawler access, llms.txt, citability, brand mention signals
- `seo-local` -- GBP signals, NAP consistency, reviews, local schema, industry-specific local factors (spawn when Local Service industry detected: brick-and-mortar, SAB, or hybrid business type)
- `seo-maps` -- Geo-grid rank tracking, GBP audit, review intelligence, competitor radius mapping (spawn when Local Service detected AND DataForSEO MCP available)
+ - `seo-google` -- CWV field data (CrUX), URL indexation (GSC), organic traffic (GA4) (spawn when Google API credentials detected via `python scripts/google_auth.py --check`)
5. **Score** -- aggregate into SEO Health Score (0-100)
6. **Report** -- generate prioritized action plan
@@ -51,6 +52,7 @@ Delay between requests: 1 second
- `FULL-AUDIT-REPORT.md`: Comprehensive findings
- `ACTION-PLAN.md`: Prioritized recommendations (Critical > High > Medium > Low)
- `screenshots/`: Desktop + mobile captures (if Playwright available)
+- **PDF Report** (recommended): Generate a professional A4 PDF using `scripts/google_report.py --type full`. This produces a white-cover enterprise report with TOC, executive summary, charts (Lighthouse gauges, query bars, index donut), metric cards, threshold tables, prioritized recommendations with effort estimates, and implementation roadmap. Always offer PDF generation after completing an audit.
## Scoring Weights
@@ -121,6 +123,10 @@ Delay between requests: 1 second
If DataForSEO MCP tools are available, spawn the `seo-dataforseo` agent alongside existing subagents to enrich the audit with live data: real SERP positions, backlink profiles with spam scores, on-page analysis (Lighthouse), business listings, and AI visibility checks (ChatGPT scraper, LLM mentions).
+## Google API Integration (Optional)
+
+If Google API credentials are configured (`python scripts/google_auth.py --check`), spawn the `seo-google` agent to enrich the audit with real Google field data: CrUX Core Web Vitals (replaces lab-only estimates), GSC URL indexation status, search performance (clicks, impressions, CTR), and GA4 organic traffic trends. The Performance (CWV) category score benefits most from field data.
+
## Error Handling
| Scenario | Action |
diff --git a/skills/seo-competitor-pages/SKILL.md b/skills/seo-competitor-pages/SKILL.md
index 8944109..8879a26 100644
--- a/skills/seo-competitor-pages/SKILL.md
+++ b/skills/seo-competitor-pages/SKILL.md
@@ -12,7 +12,7 @@ license: MIT
allowed-tools: Read, Grep, Glob, Bash, WebFetch
metadata:
author: AgriciDaniel
- version: "1.6.1"
+ version: "1.7.0"
category: seo
---
diff --git a/skills/seo-content/SKILL.md b/skills/seo-content/SKILL.md
index 719e9b0..4038849 100644
--- a/skills/seo-content/SKILL.md
+++ b/skills/seo-content/SKILL.md
@@ -10,7 +10,7 @@ license: MIT
allowed-tools: Read, Grep, Glob, Bash, WebFetch
metadata:
author: AgriciDaniel
- version: "1.6.1"
+ version: "1.7.0"
category: seo
---
diff --git a/skills/seo-dataforseo/SKILL.md b/skills/seo-dataforseo/SKILL.md
index 7f75c67..1020615 100644
--- a/skills/seo-dataforseo/SKILL.md
+++ b/skills/seo-dataforseo/SKILL.md
@@ -16,7 +16,7 @@ allowed-tools: Read, Grep, Glob, Bash, WebFetch, Write
compatibility: "Requires DataForSEO MCP server"
metadata:
author: AgriciDaniel
- version: "1.6.1"
+ version: "1.7.0"
category: seo
---
diff --git a/skills/seo-geo/SKILL.md b/skills/seo-geo/SKILL.md
index c106425..a8df7eb 100644
--- a/skills/seo-geo/SKILL.md
+++ b/skills/seo-geo/SKILL.md
@@ -14,7 +14,7 @@ license: MIT
allowed-tools: Read, Grep, Glob, Bash, WebFetch
metadata:
author: AgriciDaniel
- version: "1.6.1"
+ version: "1.7.0"
category: seo
---
diff --git a/skills/seo-google/SKILL.md b/skills/seo-google/SKILL.md
new file mode 100644
index 0000000..0db77c0
--- /dev/null
+++ b/skills/seo-google/SKILL.md
@@ -0,0 +1,346 @@
+---
+name: seo-google
+description: >
+ Google SEO APIs: Search Console (Search Analytics, URL Inspection, Sitemaps),
+ PageSpeed Insights v5, CrUX field data with 25-week history, Indexing API v3,
+ and GA4 organic traffic. Provides real Google field data for Core Web Vitals,
+ indexation status, search performance, and organic traffic trends. Use when
+ user says "search console", "GSC", "PageSpeed", "CrUX", "field data",
+ "indexing API", "GA4 organic", "URL inspection", "google api setup",
+ "real CWV data", "impressions", "clicks", "CTR", "position data",
+ "LCP", "INP", "CLS", "FCP", "TTFB", or "Lighthouse scores".
+user-invokable: true
+argument-hint: "[command] [url|property]"
+license: MIT
+allowed-tools: Read, Grep, Glob, Bash, WebFetch, Write
+metadata:
+ author: AgriciDaniel
+ version: "1.7.0"
+ category: seo
+---
+
+# Google SEO APIs
+
+Direct access to Google's own SEO data. Bridges the gap between crawl-based
+analysis (existing claude-seo skills) and Google's real-time field data: actual
+Chrome user metrics, real indexation status, search performance, and organic traffic.
+
+All APIs are free. Setup requires a Google Cloud project with API key and/or
+service account -- run `/seo google setup` for step-by-step instructions.
+
+## Prerequisites
+
+Before executing any command, check credentials:
+```bash
+python scripts/google_auth.py --check --json
+```
+
+Config file: `~/.config/claude-seo/google-api.json`
+```json
+{
+ "service_account_path": "/path/to/service_account.json",
+ "api_key": "AIzaSy...",
+ "default_property": "sc-domain:example.com",
+ "ga4_property_id": "properties/123456789"
+}
+```
+
+If missing, read `references/auth-setup.md` and walk the user through setup.
+
+### Credential Tiers
+
+| Tier | Detection | Available Commands |
+|------|-----------|-------------------|
+| **0** (API Key) | `api_key` present | `pagespeed`, `crux`, `crux-history`, `youtube`, `nlp` |
+| **1** (OAuth/SA) | + OAuth token or service account | Tier 0 + `gsc`, `inspect`, `sitemaps`, `index` |
+| **2** (Full) | + `ga4_property_id` configured | Tier 1 + `ga4`, `ga4-pages` |
+| **3** (Ads) | + `ads_developer_token` + `ads_customer_id` | Tier 2 + `keywords`, `volume` |
+
+Always communicate the detected tier before running commands.
+
+## Quick Reference
+
+| Command | What it does | Tier |
+|---------|-------------|------|
+| `/seo google setup` | Check/configure API credentials | -- |
+| `/seo google pagespeed <url>` | PSI Lighthouse + CrUX field data | 0 |
+| `/seo google crux <url>` | CrUX field data only (p75 metrics) | 0 |
+| `/seo google crux-history <url>` | 25-week CWV trend analysis | 0 |
+| `/seo google gsc <property>` | Search Console: clicks, impressions, CTR, position | 1 |
+| `/seo google inspect <url>` | URL Inspection: index status, canonical, crawl info | 1 |
+| `/seo google inspect-batch <file>` | Batch URL Inspection from file | 1 |
+| `/seo google sitemaps <property>` | GSC sitemap status | 1 |
+| `/seo google index <url>` | Submit URL to Indexing API | 1 |
+| `/seo google index-batch <file>` | Batch submit up to 200 URLs | 1 |
+| `/seo google ga4 [property-id]` | GA4 organic traffic report | 2 |
+| `/seo google ga4-pages [property-id]` | Top organic landing pages | 2 |
+| `/seo google youtube <query>` | YouTube video search (views, likes, duration) | 0 |
+| `/seo google youtube-video <id>` | YouTube video details + top comments | 0 |
+| `/seo google nlp <url-or-text>` | NLP entity extraction + sentiment + classification | 0 |
+| `/seo google entities <url-or-text>` | Entity analysis only (for E-E-A-T) | 0 |
+| `/seo google keywords <seed>` | Keyword ideas from Google Ads Keyword Planner | 3 |
+| `/seo google volume <keywords>` | Search volume lookup from Keyword Planner | 3 |
+| `/seo google entity <query>` | Knowledge Graph entity check | 0 |
+| `/seo google safety <url>` | Web Risk URL safety check | 0 |
+| `/seo google quotas` | Show rate limits for all APIs | -- |
+
+---
+
+## PageSpeed + CrUX
+
+### `/seo google pagespeed <url>`
+
+Combined Lighthouse lab data + CrUX field data.
+
+**Script:** `python scripts/pagespeed_check.py <url> --json`
+**Reference:** `references/pagespeed-crux-api.md`
+**Default:** Both mobile + desktop strategies, all Lighthouse categories.
+
+Output merges lab scores (point-in-time Lighthouse) with field data (28-day
+Chrome user metrics). CrUX tries URL-level first, falls back to origin-level.
+
+### `/seo google crux <url>`
+
+CrUX field data only (no Lighthouse run). Faster.
+
+**Script:** `python scripts/pagespeed_check.py <url> --crux-only --json`
+
+### `/seo google crux-history <url>`
+
+25-week CrUX History trends. Shows whether CWV metrics are improving, stable, or degrading.
+
+**Script:** `python scripts/crux_history.py <url> --json`
+**Reference:** `references/pagespeed-crux-api.md`
+
+Output includes per-metric trend direction, percentage change, and weekly p75 values.
+
+---
+
+## Search Console
+
+### `/seo google gsc <property>`
+
+Search Analytics: clicks, impressions, CTR, position for last 28 days.
+
+**Script:** `python scripts/gsc_query.py --property <property> --json`
+**Reference:** `references/search-console-api.md`
+**Default:** 28 days, dimensions=query,page, type=web, limit=1000.
+
+Includes quick-win detection: queries at position 4-10 with high impressions.
+
+### `/seo google inspect <url>`
+
+URL Inspection: real indexation status from Google.
+
+**Script:** `python scripts/gsc_inspect.py <url> --json`
+
+Returns: verdict (PASS/FAIL), coverage state, robots.txt status, indexing state,
+page fetch state, canonical selection, mobile usability, rich results.
+
+### `/seo google inspect-batch <file>`
+
+Batch inspection from a file (one URL per line). Rate limited to 2,000/day per site.
+
+**Script:** `python scripts/gsc_inspect.py --batch <file> --json`
+
+### `/seo google sitemaps <property>`
+
+List submitted sitemaps with status, errors, warnings.
+
+**Script:** `python scripts/gsc_query.py sitemaps --property <property> --json`
+
+---
+
+## Indexing API
+
+### `/seo google index <url>`
+
+Notify Google of a URL update.
+
+**Script:** `python scripts/indexing_notify.py <url> --json`
+**Reference:** `references/indexing-api.md`
+
+The Indexing API is officially for JobPosting and BroadcastEvent/VideoObject pages.
+Always inform the user of this restriction. Daily quota: 200 publish requests.
+
+### `/seo google index-batch <file>`
+
+Batch submit URLs from a file. Tracks quota usage.
+
+**Script:** `python scripts/indexing_notify.py --batch <file> --json`
+
+---
+
+## GA4 Traffic
+
+### `/seo google ga4 [property-id]`
+
+Organic traffic report: daily sessions, users, pageviews, bounce rate, engagement.
+
+**Script:** `python scripts/ga4_report.py --property <id> --json`
+**Reference:** `references/ga4-data-api.md`
+**Default:** 28 days, filtered to Organic Search channel group.
+
+### `/seo google ga4-pages [property-id]`
+
+Top organic landing pages ranked by sessions.
+
+**Script:** `python scripts/ga4_report.py --property <id> --report top-pages --json`
+
+---
+
+## YouTube (Video SEO)
+
+YouTube mentions have the strongest AI visibility correlation (0.737). Free, API key only.
+
+### `/seo google youtube <query>`
+
+Search YouTube for videos. Returns title, channel, views, likes, duration.
+
+**Script:** `python scripts/youtube_search.py search "<query>" --json`
+**Reference:** `references/youtube-api.md`
+**Quota:** 100 units per search (10,000 units/day free).
+
+### `/seo google youtube-video <video_id>`
+
+Detailed video info + tags + top 10 comments.
+
+**Script:** `python scripts/youtube_search.py video <video_id> --json`
+**Quota:** 2 units (video details + comments).
+
+---
+
+## NLP Content Analysis
+
+Google's own entity/sentiment analysis. Enhances E-E-A-T scoring.
+
+### `/seo google nlp <url-or-text>`
+
+Full NLP analysis: entities, sentiment, content classification.
+
+**Script:** `python scripts/nlp_analyze.py --url <url> --json` or `--text "..."`
+**Reference:** `references/nlp-api.md`
+**Free tier:** 5,000 units/month. Requires billing enabled on GCP project.
+
+### `/seo google entities <url-or-text>`
+
+Entity extraction only (faster, less quota).
+
+**Script:** `python scripts/nlp_analyze.py --url <url> --features entities --json`
+
+---
+
+## Keyword Research (Google Ads)
+
+Gold-standard keyword volume data. Requires Google Ads account.
+
+### `/seo google keywords <seed>`
+
+Generate keyword ideas from seed terms.
+
+**Script:** `python scripts/keyword_planner.py ideas "<seed>" --json`
+**Reference:** `references/keyword-planner-api.md`
+**Requires:** Ads developer token + customer ID in config (Tier 3).
+
+### `/seo google volume <keywords>`
+
+Search volume for specific keywords (comma-separated).
+
+**Script:** `python scripts/keyword_planner.py volume "<kw1>,<kw2>" --json`
+
+---
+
+## Supplementary
+
+### `/seo google entity <query>`
+
+Knowledge Graph entity check. Verifies brand presence.
+
+**Reference:** `references/supplementary-apis.md`
+Uses Knowledge Graph Search API with API key.
+
+### `/seo google safety <url>`
+
+Web Risk API check for malware/social engineering flags.
+
+**Reference:** `references/supplementary-apis.md`
+
+### `/seo google quotas`
+
+Display rate limits table. Read `references/rate-limits-quotas.md`.
+
+---
+
+## Reports
+
+After any analysis command, offer to generate a PDF/HTML report.
+
+### `/seo google report <type>`
+
+Generate a professional PDF report with charts and analytics.
+
+**Script:** `python scripts/google_report.py --type <type> --data <json> --domain <domain> --format pdf`
+
+| Type | Input | Output |
+|------|-------|--------|
+| `cwv-audit` | PSI + CrUX + CrUX History data | Core Web Vitals audit with gauges, timelines, distributions |
+| `gsc-performance` | GSC query data | Search Console report with query tables, quick wins |
+| `indexation` | Batch inspection data | Indexation status with coverage donut chart |
+| `full` | All data combined | Comprehensive Google SEO report (all sections) |
+
+**Workflow:**
+1. Run data collection commands (pagespeed, gsc, inspect-batch, etc.)
+2. Save JSON output to file: `python scripts/pagespeed_check.py <url> --json > data.json`
+3. Generate report: `python scripts/google_report.py --type cwv-audit --data data.json --domain <domain>`
+
+**Convention:** After completing analysis, suggest: "Generate a report? Use `/seo google report <type>`"
+
+---
+
+## Rate Limits
+
+| API | Per-Minute | Per-Day | Auth |
+|-----|-----------|---------|------|
+| PSI v5 | 240 QPM | 25,000 QPD | API Key |
+| CrUX + History | 150 QPM (shared) | Unlimited | API Key |
+| GSC Search Analytics | 1,200 QPM/site | 30M QPD | Service Account |
+| GSC URL Inspection | 600 QPM | 2,000 QPD/site | Service Account |
+| Indexing API | 380 RPM | 200 publish/day | Service Account |
+| GA4 Data API | 10 concurrent | ~25K tokens/day | Service Account |
+
+## Cross-Skill Integration
+
+- **seo-audit**: Spawns `seo-google` agent for live CWV + indexation data (conditional)
+- **seo-technical**: Uses pagespeed_check.py for real CWV field data
+- **seo-performance**: CrUX field data supplements Lighthouse lab data
+- **seo-sitemap**: GSC sitemap status shows real crawl/index coverage
+- **seo-content**: GSC query data informs keyword targeting
+- **seo-geo**: GSC search appearance data includes AI Overview references
+
+## Output Format
+
+- CWV metrics: traffic-light rating (Good / Needs Improvement / Poor)
+- Performance reports: tables with sortable columns
+- Always include data freshness note
+- Save reports as `GOOGLE-API-REPORT-{domain}.md`
+- Use templates from `assets/templates/` for structured output
+
+## Technical Notes
+
+- INP replaced FID on March 12, 2024. Never reference FID.
+- CLS values from CrUX are string-encoded (e.g., "0.05"). Scripts handle parsing.
+- CrUX 404 = insufficient traffic, not an auth error.
+- Search Analytics data has 2-3 day lag.
+- `round_trip_time` replaced `effectiveConnectionType` in CrUX (Feb 2025).
+- Custom Search JSON API is closed to new customers (2025).
+
+## Error Handling
+
+| Scenario | Action |
+|----------|--------|
+| No credentials configured | Run `/seo google setup`. List Tier 0 commands that work with just an API key. |
+| Service account lacks GSC access | Report error. Instruct: add `client_email` to GSC > Settings > Users > Add. |
+| CrUX data unavailable (404) | Report insufficient Chrome traffic. Suggest PSI lab data as fallback. |
+| GA4 property not found | Report error. Show how to find property ID in GA4 Admin > Property Details. |
+| Indexing API quota exceeded | Report 200/day limit. Suggest prioritizing most important URLs. |
+| Rate limit (429) | Wait and retry with exponential backoff. Report which API hit the limit. |
diff --git a/skills/seo-google/assets/templates/cwv-audit-report.md b/skills/seo-google/assets/templates/cwv-audit-report.md
new file mode 100644
index 0000000..0e97889
--- /dev/null
+++ b/skills/seo-google/assets/templates/cwv-audit-report.md
@@ -0,0 +1,48 @@
+# Core Web Vitals Audit
+
+**URL/Origin:** {target}
+**Strategy:** {strategy}
+
+## CrUX Field Data (28-day rolling average)
+
+Real Chrome user experience data from the Chrome UX Report.
+
+| Metric | p75 Value | Rating | Good Threshold | Distribution |
+|--------|-----------|--------|----------------|-------------|
+| LCP | {lcp_value} | {lcp_rating} | ≤ 2,500ms | Good: {lcp_good}% / NI: {lcp_ni}% / Poor: {lcp_poor}% |
+| INP | {inp_value} | {inp_rating} | ≤ 200ms | Good: {inp_good}% / NI: {inp_ni}% / Poor: {inp_poor}% |
+| CLS | {cls_value} | {cls_rating} | ≤ 0.1 | Good: {cls_good}% / NI: {cls_ni}% / Poor: {cls_poor}% |
+| FCP | {fcp_value} | {fcp_rating} | ≤ 1,800ms | Good: {fcp_good}% / NI: {fcp_ni}% / Poor: {fcp_poor}% |
+| TTFB | {ttfb_value} | {ttfb_rating} | ≤ 800ms | Good: {ttfb_good}% / NI: {ttfb_ni}% / Poor: {ttfb_poor}% |
+
+**Collection Period:** {collection_start} to {collection_end}
+
+## Lighthouse Lab Scores
+
+| Category | Score |
+|----------|-------|
+| Performance | {perf_score}/100 |
+| Accessibility | {a11y_score}/100 |
+| Best Practices | {bp_score}/100 |
+| SEO | {seo_score}/100 |
+
+## CrUX History Trends (25-week)
+
+| Metric | Direction | Change | Earliest → Latest |
+|--------|-----------|--------|-------------------|
+{trends_table}
+
+## Top Opportunities
+
+| Opportunity | Estimated Savings |
+|-------------|-------------------|
+{opportunities_table}
+
+## Recommendations
+
+{recommendations}
+
+---
+*CrUX data updated daily ~04:00 UTC. 28-day rolling average.*
+*INP replaced FID as the responsiveness Core Web Vital on March 12, 2024.*
+*Generated {timestamp}.*
diff --git a/skills/seo-google/assets/templates/gsc-performance-report.md b/skills/seo-google/assets/templates/gsc-performance-report.md
new file mode 100644
index 0000000..9a19a80
--- /dev/null
+++ b/skills/seo-google/assets/templates/gsc-performance-report.md
@@ -0,0 +1,44 @@
+# Google Search Console Performance Report
+
+**Property:** {property}
+**Date Range:** {start_date} — {end_date}
+**Search Type:** {search_type}
+
+## Summary
+
+| Metric | Value |
+|--------|-------|
+| Total Clicks | {total_clicks} |
+| Total Impressions | {total_impressions} |
+| Average CTR | {avg_ctr}% |
+| Average Position | {avg_position} |
+
+## Top Queries
+
+| # | Query | Clicks | Impressions | CTR | Position |
+|---|-------|--------|-------------|-----|----------|
+{queries_table}
+
+## Top Pages
+
+| # | Page | Clicks | Impressions | CTR | Position |
+|---|------|--------|-------------|-----|----------|
+{pages_table}
+
+## Quick Wins (Position 4-10, High Impressions)
+
+These queries rank on page 1 but below position 3. A small ranking improvement could yield significant traffic gains.
+
+| Query | Position | Impressions | Clicks | CTR | Opportunity |
+|-------|----------|-------------|--------|-----|-------------|
+{quick_wins_table}
+
+## Device Breakdown
+
+| Device | Clicks | Impressions | CTR | Position |
+|--------|--------|-------------|-----|----------|
+{device_table}
+
+---
+*Data freshness: Search Analytics has a 2-3 day lag. Data available for ~16 months.*
+*Generated {timestamp} via Google Search Console API.*
diff --git a/skills/seo-google/assets/templates/indexation-status-report.md b/skills/seo-google/assets/templates/indexation-status-report.md
new file mode 100644
index 0000000..c7d2ec0
--- /dev/null
+++ b/skills/seo-google/assets/templates/indexation-status-report.md
@@ -0,0 +1,43 @@
+# URL Indexation Status Report
+
+**Property:** {property}
+**URLs Inspected:** {total_urls}
+
+## Summary
+
+| Status | Count | Percentage |
+|--------|-------|-----------|
+| Indexed (PASS) | {pass_count} | {pass_pct}% |
+| Not Indexed (FAIL) | {fail_count} | {fail_pct}% |
+| Neutral | {neutral_count} | {neutral_pct}% |
+| Errors | {error_count} | {error_pct}% |
+
+## Detailed Results
+
+| URL | Verdict | Coverage State | Fetch State | Google Canonical | Last Crawl |
+|-----|---------|---------------|-------------|-----------------|------------|
+{results_table}
+
+## Canonical Mismatches
+
+URLs where Google selected a different canonical than declared:
+
+| URL | User Canonical | Google Canonical |
+|-----|---------------|-----------------|
+{canonical_mismatches_table}
+
+## Common Issues
+
+| Issue | Count | Priority | Action |
+|-------|-------|----------|--------|
+{issues_table}
+
+## Rich Results Detected
+
+| URL | Rich Result Type | Status |
+|-----|-----------------|--------|
+{rich_results_table}
+
+---
+*URL Inspection API: 2,000 inspections/day per site, 600/min.*
+*Generated {timestamp} via Google Search Console URL Inspection API.*
diff --git a/skills/seo-google/references/auth-setup.md b/skills/seo-google/references/auth-setup.md
new file mode 100644
index 0000000..255f666
--- /dev/null
+++ b/skills/seo-google/references/auth-setup.md
@@ -0,0 +1,154 @@
+# Google API Authentication Setup
+
+## Overview
+
+Three credential types serve different APIs:
+
+| Type | Used By | Cost |
+|------|---------|------|
+| **API Key** | PageSpeed Insights, CrUX, CrUX History, Knowledge Graph | Free |
+| **Service Account** | Search Console, Indexing API, GA4 | Free |
+| **Both** | Full seo-google skill | Free |
+
+## Step 1: Create a Google Cloud Project
+
+1. Go to [console.cloud.google.com](https://console.cloud.google.com)
+2. Click **Select a project** > **New Project**
+3. Name it (e.g., "Claude SEO") and note the project ID
+4. Select the project after creation
+
+## Step 2: Enable APIs
+
+Navigate to **APIs & Services > Library** and enable:
+
+| API | Required For |
+|-----|-------------|
+| Google Search Console API | GSC Search Analytics, URL Inspection, Sitemaps |
+| PageSpeed Insights API | PSI Lighthouse lab data |
+| Chrome UX Report API | CrUX field data + History |
+| Web Search Indexing API | Indexing API v3 |
+| Google Analytics Data API | GA4 organic traffic |
+| Knowledge Graph Search API | Entity verification (optional) |
+
+## Step 3: Create an API Key
+
+1. **APIs & Services > Credentials > Create Credentials > API key**
+2. Click **Restrict key**:
+ - Under **API restrictions**, select: PageSpeed Insights API, Chrome UX Report API, Knowledge Graph Search API
+3. Copy the key (starts with `AIzaSy...`)
+
+## Step 4: Create a Service Account
+
+1. **IAM & Admin > Service Accounts > Create Service Account**
+2. Name: `claude-seo` (or similar)
+3. Skip optional permissions steps
+4. Click on the created service account > **Keys > Add Key > Create new key > JSON**
+5. Download the JSON file and store it securely (e.g., `~/.config/claude-seo/service_account.json`)
+
+The JSON file looks like:
+```json
+{
+ "type": "service_account",
+ "project_id": "your-project-id",
+ "private_key_id": "...",
+ "private_key": "-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----\n",
+ "client_email": "[email protected]",
+ "client_id": "...",
+ "auth_uri": "https://accounts.google.com/o/oauth2/auth",
+ "token_uri": "https://oauth2.googleapis.com/token"
+}
+```
+
+The `client_email` field is what you add to GSC and GA4.
+
+## Step 5: Grant Search Console Access
+
+1. Go to [Google Search Console](https://search.google.com/search-console)
+2. Select your property
+3. **Settings > Users and permissions > Add user**
+4. Paste the service account `client_email`
+5. Set permission level:
+ - **Full** for read-only (Search Analytics, URL Inspection, Sitemaps)
+ - **Owner** if you also need the Indexing API
+
+## Step 6: Grant GA4 Access
+
+1. Go to [Google Analytics](https://analytics.google.com)
+2. **Admin > Property Access Management > Add users** (the + icon)
+3. Paste the service account `client_email`
+4. Set role: **Viewer** (minimum for read-only reporting)
+5. Note the numeric property ID from **Admin > Property Details** (e.g., `123456789`)
+
+## Step 7: Create Config File
+
+```bash
+mkdir -p ~/.config/claude-seo
+```
+
+Save to `~/.config/claude-seo/google-api.json`:
+
+```json
+{
+ "service_account_path": "~/.config/claude-seo/service_account.json",
+ "api_key": "AIzaSy...",
+ "default_property": "sc-domain:example.com",
+ "ga4_property_id": "properties/123456789"
+}
+```
+
+### Property URL Formats
+
+| Format | Example | When to Use |
+|--------|---------|-------------|
+| Domain property | `sc-domain:example.com` | Covers all URLs on the domain (recommended) |
+| URL-prefix property | `https://example.com/` | Covers only that specific prefix |
+
+## Step 8: Verify Setup
+
+```bash
+python scripts/google_auth.py --check
+```
+
+Expected output at Tier 2 (full):
+```
+Credential Tier: 2 -- Full (API key + Service Account + GA4)
+
+ [OK] PageSpeed Insights v5
+ [OK] Chrome UX Report (CrUX) API
+ [OK] CrUX History API
+ [OK] Google Search Console API
+ Service account: [email protected]
+ [OK] Google Indexing API v3
+ [OK] GA4 Data API v1beta
+```
+
+## Environment Variable Alternatives
+
+Instead of (or in addition to) the config file:
+
+| Variable | Purpose |
+|----------|---------|
+| `GOOGLE_API_KEY` | API key for PSI/CrUX |
+| `GOOGLE_APPLICATION_CREDENTIALS` | Path to service account JSON |
+| `GA4_PROPERTY_ID` | GA4 property (e.g., `properties/123456789`) |
+| `GSC_PROPERTY` | Default GSC property (e.g., `sc-domain:example.com`) |
+
+## OAuth Scopes Used
+
+| Scope | APIs |
+|-------|------|
+| `https://www.googleapis.com/auth/webmasters.readonly` | GSC (read) |
+| `https://www.googleapis.com/auth/webmasters` | GSC (read/write, needed for sitemap submission) |
+| `https://www.googleapis.com/auth/indexing` | Indexing API |
+| `https://www.googleapis.com/auth/analytics.readonly` | GA4 (read) |
+
+## Troubleshooting
+
+| Error | Fix |
+|-------|-----|
+| `403 Forbidden` on GSC | Service account email not added to GSC property, or wrong permission level |
+| `403 Forbidden` on GA4 | Service account email not added to GA4 property as Viewer |
+| `404 Not Found` on GSC | Wrong property URL format. Use `sc-domain:` or include trailing slash for URL-prefix |
+| `404 Not Found` on CrUX | Site has insufficient Chrome traffic. Not a credentials issue. |
+| `429 Rate Limit` | Wait and retry. See rate-limits-quotas.md for per-API limits |
+| `API not enabled` | Enable the specific API in GCP Console > APIs & Services > Library |
diff --git a/skills/seo-google/references/ga4-data-api.md b/skills/seo-google/references/ga4-data-api.md
new file mode 100644
index 0000000..870a9af
--- /dev/null
+++ b/skills/seo-google/references/ga4-data-api.md
@@ -0,0 +1,184 @@
+# GA4 Data API v1beta Reference
+
+## Overview
+
+The Google Analytics Data API v1beta provides programmatic access to GA4 report data. For SEO, the primary use case is organic traffic analysis.
+
+**Base URL:** `https://analyticsdata.googleapis.com/v1beta`
+
+## Key Methods
+
+| Method | Description |
+|--------|-------------|
+| `properties.runReport` | Run a standard report |
+| `properties.batchRunReports` | Up to 5 reports in one call |
+| `properties.runRealtimeReport` | Last 30 minutes of data |
+| `properties.getMetadata` | Available dimensions and metrics |
+| `properties.checkCompatibility` | Verify dimension/metric combinations |
+
+## runReport Request
+
+```json
+{
+ "property": "properties/123456789",
+ "dimensions": [
+ { "name": "date" },
+ { "name": "landingPage" }
+ ],
+ "metrics": [
+ { "name": "sessions" },
+ { "name": "totalUsers" }
+ ],
+ "dateRanges": [
+ { "startDate": "28daysAgo", "endDate": "yesterday" }
+ ],
+ "dimensionFilter": {
+ "filter": {
+ "fieldName": "sessionDefaultChannelGroup",
+ "stringFilter": {
+ "matchType": "EXACT",
+ "value": "Organic Search"
+ }
+ }
+ },
+ "orderBys": [
+ { "metric": { "metricName": "sessions" }, "desc": true }
+ ],
+ "limit": 100,
+ "returnPropertyQuota": true
+}
+```
+
+## SEO-Relevant Dimensions
+
+| Dimension | Description |
+|-----------|-------------|
+| `date` | Date in YYYYMMDD format |
+| `pagePath` | Page path (e.g., `/blog/post`) |
+| `landingPage` | Entry page path |
+| `landingPagePlusQueryString` | Entry page with query params |
+| `fullPageUrl` | Full page URL |
+| `pageTitle` | Page title |
+| `sessionSource` | Traffic source (e.g., `google`) |
+| `sessionMedium` | Traffic medium (e.g., `organic`) |
+| `sessionDefaultChannelGroup` | Channel grouping (e.g., `Organic Search`) |
+| `country` | User country |
+| `deviceCategory` | `desktop`, `mobile`, `tablet` |
+| `hostName` | Domain name |
+| `pageReferrer` | Referrer URL |
+
+## SEO-Relevant Metrics
+
+| Metric | Description |
+|--------|-------------|
+| `sessions` | Number of sessions |
+| `totalUsers` | Total unique users |
+| `newUsers` | First-time users |
+| `activeUsers` | Users with engagement |
+| `screenPageViews` | Page views |
+| `bounceRate` | Bounce rate (0-1, multiply by 100 for %) |
+| `averageSessionDuration` | Avg duration in seconds |
+| `engagementRate` | Engaged session rate (0-1) |
+| `keyEvents` | Key events (replaced deprecated `conversions`) |
+| `eventCount` | Total event count |
+
+## Filter Expressions
+
+### String Filter
+
+```json
+{
+ "filter": {
+ "fieldName": "sessionDefaultChannelGroup",
+ "stringFilter": {
+ "matchType": "EXACT",
+ "value": "Organic Search"
+ }
+ }
+}
+```
+
+Match types: `EXACT`, `BEGINS_WITH`, `ENDS_WITH`, `CONTAINS`, `FULL_REGEXP`, `PARTIAL_REGEXP`
+
+### Combining Filters
+
+```json
+{
+ "andGroup": {
+ "expressions": [
+ { "filter": { "fieldName": "country", "stringFilter": { "matchType": "EXACT", "value": "US" }}},
+ { "filter": { "fieldName": "deviceCategory", "stringFilter": { "matchType": "EXACT", "value": "mobile" }}}
+ ]
+ }
+}
+```
+
+Also supports `orGroup` and `notExpression`.
+
+## Date Range Shortcuts
+
+| Value | Meaning |
+|-------|---------|
+| `today` | Current day |
+| `yesterday` | Previous day |
+| `NdaysAgo` | N days ago (e.g., `28daysAgo`) |
+| `YYYY-MM-DD` | Specific date |
+
+Up to 4 date ranges per request (for period-over-period comparison).
+
+## Token-Based Quotas
+
+| Quota | Limit | Scope |
+|-------|-------|-------|
+| Daily tokens | 25,000 | Per property per project |
+| Hourly tokens | 5,000 | Per property per project |
+| Concurrent requests | 10 | Per property per project |
+| Hourly tokens (project-wide) | 1,250 | Per project per property per hour |
+
+Set `returnPropertyQuota: true` to monitor consumption. Simple reports cost ~1-10 tokens; complex ones up to ~100.
+
+## Python Example
+
+```python
+from google.analytics.data_v1beta import BetaAnalyticsDataClient
+from google.analytics.data_v1beta.types import (
+ DateRange, Dimension, Filter, FilterExpression,
+ Metric, OrderBy, RunReportRequest,
+)
+from google.oauth2 import service_account
+
+credentials = service_account.Credentials.from_service_account_file(
+ "service_account.json",
+ scopes=["https://www.googleapis.com/auth/analytics.readonly"],
+)
+
+client = BetaAnalyticsDataClient(credentials=credentials)
+
+request = RunReportRequest(
+ property="properties/123456789",
+ dimensions=[Dimension(name="landingPage")],
+ metrics=[Metric(name="sessions"), Metric(name="totalUsers")],
+ date_ranges=[DateRange(start_date="28daysAgo", end_date="yesterday")],
+ dimension_filter=FilterExpression(
+ filter=Filter(
+ field_name="sessionDefaultChannelGroup",
+ string_filter=Filter.StringFilter(
+ match_type=Filter.StringFilter.MatchType.EXACT,
+ value="Organic Search",
+ ),
+ )
+ ),
+ order_bys=[OrderBy(metric=OrderBy.MetricOrderBy(metric_name="sessions"), desc=True)],
+ limit=50,
+ return_property_quota=True,
+)
+
+response = client.run_report(request)
+for row in response.rows:
+ print(f"{row.dimension_values[0].value}: {row.metric_values[0].value} sessions")
+```
+
+## Authentication
+- **Scope:** `https://www.googleapis.com/auth/analytics.readonly`
+- Service account must have **Viewer** role in GA4 property
+- Add via GA4 Admin > Property Access Management
diff --git a/skills/seo-google/references/indexing-api.md b/skills/seo-google/references/indexing-api.md
new file mode 100644
index 0000000..ef23cae
--- /dev/null
+++ b/skills/seo-google/references/indexing-api.md
@@ -0,0 +1,107 @@
+# Google Indexing API v3 Reference
+
+## Overview
+
+The Indexing API allows you to notify Google when pages are added or removed.
+
+**IMPORTANT:** Officially restricted to pages with **JobPosting** or **BroadcastEvent/VideoObject** structured data. Google may process other page types, but provides no guarantees. Always inform users of this limitation.
+
+## Endpoints
+
+### Publish Notification
+
+**`POST https://indexing.googleapis.com/v3/urlNotifications:publish`**
+
+```json
+{
+ "url": "https://example.com/jobs/software-engineer",
+ "type": "URL_UPDATED"
+}
+```
+
+| Field | Values |
+|-------|--------|
+| `url` | The fully qualified URL |
+| `type` | `URL_UPDATED` (page added/changed), `URL_DELETED` (page removed) |
+
+**Response:**
+```json
+{
+ "urlNotificationMetadata": {
+ "url": "https://example.com/jobs/software-engineer",
+ "latestUpdate": {
+ "url": "https://example.com/jobs/software-engineer",
+ "type": "URL_UPDATED",
+ "notifyTime": "2026-03-27T10:00:00Z"
+ }
+ }
+}
+```
+
+### Get Notification Metadata
+
+**`GET https://indexing.googleapis.com/v3/urlNotifications/metadata?url={ENCODED_URL}`**
+
+Returns `latestUpdate` and `latestRemove` timestamps for the URL.
+
+### Batch Requests
+
+**`POST https://indexing.googleapis.com/batch`**
+
+Up to **100 URLs** per batch request using `multipart/mixed` format:
+
+```
+POST /batch HTTP/1.1
+Content-Type: multipart/mixed; boundary=batch_boundary
+
+--batch_boundary
+Content-Type: application/http
+Content-ID: <item1>
+
+POST /v3/urlNotifications:publish HTTP/1.1
+Content-Type: application/json
+
+{"url": "https://example.com/jobs/1", "type": "URL_UPDATED"}
+--batch_boundary
+Content-Type: application/http
+Content-ID: <item2>
+
+POST /v3/urlNotifications:publish HTTP/1.1
+Content-Type: application/json
+
+{"url": "https://example.com/jobs/2", "type": "URL_UPDATED"}
+--batch_boundary--
+```
+
+## Authentication
+
+- **Scope:** `https://www.googleapis.com/auth/indexing`
+- **Auth type:** Service account (OAuth 2.0)
+- The service account must be **Owner** in Google Search Console for the target domain
+
+## Quotas
+
+| Limit | Value | Scope |
+|-------|-------|-------|
+| Publish requests | **200/day** (default) | Per project |
+| Read-only requests | 180/min | Per project |
+| Total requests | 380/min | Per project |
+
+Request a quota increase: [Indexing API Quota Increase Form](https://developers.google.com/search/apis/indexing-api/v3/quota-increase)
+
+## Error Codes
+
+| Code | Meaning | Action |
+|------|---------|--------|
+| 400 | Malformed URL or request body | Check URL format |
+| 403 | Permission denied or quota exceeded | Add service account as Owner in GSC, or check quota |
+| 429 | Rate limit exceeded | Back off and retry with exponential delay |
+| 500/503 | Server error | Retry with exponential backoff |
+
+## Best Practices
+
+1. Submit only URLs with actual content changes (don't spam updates)
+2. Use `URL_DELETED` only when a page is permanently removed (returns 404/410)
+3. Track daily quota usage -- the 200/day limit resets at midnight Pacific Time
+4. For large-scale indexing, use XML sitemaps + Search Console instead
+5. Batch requests count individually against the daily quota (100 batch = 100 quota)
diff --git a/skills/seo-google/references/keyword-planner-api.md b/skills/seo-google/references/keyword-planner-api.md
new file mode 100644
index 0000000..bd065aa
--- /dev/null
+++ b/skills/seo-google/references/keyword-planner-api.md
@@ -0,0 +1,66 @@
+# Google Ads API - Keyword Planner Reference
+
+Gold-standard source for keyword search volume. DataForSEO gets its volume data from Google Ads -- this cuts out the middleman.
+
+## Prerequisites (More Complex Than Other Google APIs)
+
+1. **Google Ads Manager Account** -- create at ads.google.com (free to create)
+2. **Developer Token** -- apply at Google Ads API Center (requires Basic access approval)
+3. **OAuth 2.0 credentials** -- reuse existing OAuth client from seo-google config
+4. **For exact volumes**: Run a minimal campaign (~$5-10/day). Without spend, volumes are bucketed ranges ("1K-10K")
+
+## Key Methods
+
+### GenerateKeywordIdeas
+Generate keyword suggestions from seed terms.
+
+**Returns per keyword:**
+- `text`: Keyword string
+- `avg_monthly_searches`: Average monthly volume (exact if spending, bucketed if not)
+- `competition`: LOW / MEDIUM / HIGH (for ads, not organic)
+- `competition_index`: 0-100 competition score
+- `low_top_of_page_bid_micros`: ~20th percentile CPC in micros
+- `high_top_of_page_bid_micros`: ~80th percentile CPC in micros
+- `monthly_search_volumes[]`: Per-month volume for last 12 months
+
+### GenerateKeywordHistoricalMetrics
+Get volume data for specific keywords.
+
+Same return fields as above but for exact keyword list instead of suggestions.
+
+### GenerateKeywordForecastMetrics
+Predict clicks, impressions, and cost for keywords.
+
+## Configuration
+
+Add to `~/.config/claude-seo/google-api.json`:
+
+```json
+{
+ "ads_developer_token": "YOUR_DEV_TOKEN",
+ "ads_customer_id": "123-456-7890",
+ "ads_login_customer_id": "123-456-7890"
+}
+```
+
+## Rate Limits
+
+- Keyword Planning requests are more strictly rate-limited than other Ads API services
+- Exact QPM/QPS not publicly documented
+- Google recommends caching results
+
+## Python Library
+
+```bash
+pip install google-ads
+```
+
+Uses `google-ads` library (separate from `google-api-python-client`).
+
+## Important Notes
+
+- **Volume accuracy**: Without active ad spend, Google returns bucketed ranges ("1K-10K", "10K-100K") instead of exact numbers like "14,800"
+- **Competition score**: Measures advertiser competition for ads, NOT organic ranking difficulty
+- **CPC bids**: Reflect what advertisers pay, useful for estimating keyword commercial value
+- **Location targeting**: Use location IDs (2840 = United States, 2826 = United Kingdom)
+- **Language targeting**: Use language IDs (1000 = English, 1003 = Spanish)
diff --git a/skills/seo-google/references/nlp-api.md b/skills/seo-google/references/nlp-api.md
new file mode 100644
index 0000000..705c84b
--- /dev/null
+++ b/skills/seo-google/references/nlp-api.md
@@ -0,0 +1,55 @@
+# Google Cloud Natural Language API Reference
+
+NLP analysis enhances E-E-A-T scoring by measuring entity coverage, content sentiment, and topic classification using Google's own taxonomy.
+
+## Endpoint
+
+`POST https://language.googleapis.com/v2/documents:annotateText?key={API_KEY}`
+
+## Features
+
+| Feature | What It Does | SEO Use |
+|---------|-------------|---------|
+| `extractEntities` | Extract people, orgs, places, events with salience scores | Topic coverage depth, entity optimization |
+| `extractDocumentSentiment` | Document + sentence-level sentiment score/magnitude | Content tone assessment |
+| `classifyText` | Map content to 700+ Google categories | Topic relevance verification |
+| `moderateText` | Content safety/moderation categories | Content quality flags |
+
+## Entity Types
+
+PERSON, LOCATION, ORGANIZATION, EVENT, WORK_OF_ART, CONSUMER_GOOD, OTHER, PHONE_NUMBER, ADDRESS, DATE, NUMBER, PRICE
+
+Each entity includes:
+- `name`: Entity text
+- `type`: Entity type
+- `salience`: Importance score (0-1, higher = more relevant)
+- `sentiment`: Per-entity sentiment (score + magnitude)
+- `metadata`: Wikipedia URL, MID (Knowledge Graph ID)
+- `mentions`: Occurrences in the text
+
+## Sentiment Scoring
+
+- **Score**: -1.0 (negative) to +1.0 (positive)
+- **Magnitude**: 0 to infinity (emotional intensity, higher = more emotional)
+- Neutral content: score ~0, low magnitude
+- Mixed content: score ~0, HIGH magnitude (both positive and negative)
+
+## Pricing
+
+| Feature | Free/month | Paid (per 1K chars) |
+|---------|-----------|-------------------|
+| Entity Analysis | 5,000 units | $0.001 |
+| Sentiment Analysis | 5,000 units | $0.001 |
+| Content Classification | 30,000 units | $0.002 |
+| Text Moderation | 50,000 units | $0.0005 |
+
+One "unit" = 1,000 characters. Free tier resets monthly.
+
+## Enable the API
+
+1. Go to [console.cloud.google.com/apis/library](https://console.cloud.google.com/apis/library)
+2. Search for "Cloud Natural Language API"
+3. Click Enable
+4. **Billing must be enabled** on the project (free tier still applies)
+
+Uses the same API key as PSI/CrUX.
diff --git a/skills/seo-google/references/pagespeed-crux-api.md b/skills/seo-google/references/pagespeed-crux-api.md
new file mode 100644
index 0000000..b33b7b8
--- /dev/null
+++ b/skills/seo-google/references/pagespeed-crux-api.md
@@ -0,0 +1,204 @@
+# PageSpeed Insights v5 + CrUX API Reference
+
+## Table of Contents
+1. [PageSpeed Insights v5](#pagespeed-insights-v5)
+2. [CrUX API (Daily)](#crux-api-daily)
+3. [CrUX History API (Weekly)](#crux-history-api-weekly)
+4. [Core Web Vitals Thresholds](#core-web-vitals-thresholds)
+
+---
+
+## PageSpeed Insights v5
+
+**Endpoint:** `GET https://www.googleapis.com/pagespeedonline/v5/runPagespeed`
+
+### Parameters
+
+| Param | Type | Description |
+|-------|------|-------------|
+| `url` | string | Required. URL to analyze. |
+| `category` | string | `ACCESSIBILITY`, `BEST_PRACTICES`, `PERFORMANCE`, `SEO`. Can specify multiple. |
+| `strategy` | string | `DESKTOP` or `MOBILE` (default). |
+| `locale` | string | Locale for text (e.g., `en`). |
+| `key` | string | API key. Optional but recommended for quota. |
+
+### Response Structure
+
+```
+{
+ "id": "https://example.com/",
+ "loadingExperience": { ... }, // URL-level CrUX data
+ "originLoadingExperience": { ... }, // Origin-level CrUX data
+ "lighthouseResult": {
+ "categories": {
+ "performance": { "score": 0.85 },
+ "accessibility": { "score": 0.92 },
+ "best-practices": { "score": 0.88 },
+ "seo": { "score": 0.95 }
+ },
+ "audits": { ... } // Individual audit results
+ },
+ "analysisUTCTimestamp": "2026-03-27T..."
+}
+```
+
+### Field Data Metrics (in loadingExperience)
+
+| PSI Key | CrUX Metric | Unit |
+|---------|-------------|------|
+| `LARGEST_CONTENTFUL_PAINT_MS` | LCP | ms |
+| `INTERACTION_TO_NEXT_PAINT` | INP | ms |
+| `CUMULATIVE_LAYOUT_SHIFT_SCORE` | CLS | unitless |
+| `FIRST_CONTENTFUL_PAINT_MS` | FCP | ms |
+| `EXPERIMENTAL_TIME_TO_FIRST_BYTE` | TTFB | ms |
+
+Each metric contains: `percentile` (p75), `distributions[]` ({min, max, proportion}), `category` (FAST/AVERAGE/SLOW/NONE).
+
+### Key Lighthouse Audit IDs
+
+`first-contentful-paint`, `largest-contentful-paint`, `total-blocking-time`, `cumulative-layout-shift`, `speed-index`, `interactive`
+
+### Rate Limits
+- 25,000 QPD with API key
+- 240 QPM
+- Free, no billing required
+
+### Note on Field Data Migration
+Google is migrating CrUX field data out of PSI. For field data, prefer the CrUX API directly. Use PSI primarily for Lighthouse lab data.
+
+---
+
+## CrUX API (Daily)
+
+**Endpoint:** `POST https://chromeuxreport.googleapis.com/v1/records:queryRecord?key={API_KEY}`
+
+### Request
+
+```json
+{
+ "origin": "https://example.com",
+ "formFactor": "PHONE",
+ "metrics": ["largest_contentful_paint", "interaction_to_next_paint", "cumulative_layout_shift"]
+}
+```
+
+| Field | Description |
+|-------|-------------|
+| `origin` | Origin URL (mutually exclusive with `url`) |
+| `url` | Specific page URL (mutually exclusive with `origin`) |
+| `formFactor` | `DESKTOP`, `PHONE`, `TABLET` (optional, omit for all) |
+| `metrics` | Array of metric names (optional, omit for all) |
+
+### Available Metrics
+
+| Metric | Type | Notes |
+|--------|------|-------|
+| `largest_contentful_paint` | int (ms) | Core Web Vital |
+| `interaction_to_next_paint` | int (ms) | Core Web Vital (replaced FID) |
+| `cumulative_layout_shift` | **string** | Core Web Vital. **String-encoded!** Parse carefully. |
+| `first_contentful_paint` | int (ms) | |
+| `experimental_time_to_first_byte` | int (ms) | |
+| `round_trip_time` | int (ms) | Replaced effectiveConnectionType (Feb 2025) |
+| `navigation_types` | fractions | navigate, navigate_cache, reload, etc. |
+| `form_factors` | fractions | desktop/phone/tablet distribution |
+
+### Response
+
+```json
+{
+ "record": {
+ "key": { "origin": "https://example.com" },
+ "metrics": {
+ "largest_contentful_paint": {
+ "histogram": [
+ { "start": 0, "end": 2500, "density": 0.72 },
+ { "start": 2500, "end": 4000, "density": 0.18 },
+ { "start": 4000, "density": 0.10 }
+ ],
+ "percentiles": { "p75": 2100 }
+ },
+ "cumulative_layout_shift": {
+ "percentiles": { "p75": "0.05" }
+ }
+ },
+ "collectionPeriod": {
+ "firstDate": { "year": 2026, "month": 2, "day": 27 },
+ "lastDate": { "year": 2026, "month": 3, "day": 26 }
+ }
+ }
+}
+```
+
+### Important
+- **CLS p75 is a string** (e.g., `"0.05"` not `0.05`). Always parse as float from string.
+- Last histogram bin has **no `end`** (extends to infinity).
+- Densities sum to approximately 1.0.
+- **404** = no data (insufficient Chrome traffic). Not an auth error.
+- Updated daily ~04:00 UTC with ~2 day lag.
+
+### Rate Limits
+- 150 QPM shared between CrUX and CrUX History APIs
+- Free, no paid increase available
+
+---
+
+## CrUX History API (Weekly)
+
+**Endpoint:** `POST https://chromeuxreport.googleapis.com/v1/records:queryHistoryRecord?key={API_KEY}`
+
+Same request format as CrUX API. Returns up to **25 weekly collection periods**.
+
+### Response Differences from CrUX API
+
+Instead of single values, returns timeseries:
+
+```json
+{
+ "record": {
+ "metrics": {
+ "largest_contentful_paint": {
+ "histogramTimeseries": [
+ { "start": 0, "end": 2500, "densities": [0.70, 0.71, 0.72, ...] },
+ { "start": 2500, "end": 4000, "densities": [0.19, 0.18, 0.18, ...] },
+ { "start": 4000, "densities": [0.11, 0.11, 0.10, ...] }
+ ],
+ "percentilesTimeseries": {
+ "p75s": [2200, 2150, 2100, ...]
+ }
+ }
+ },
+ "collectionPeriods": [
+ {
+ "firstDate": { "year": 2025, "month": 9, "day": 29 },
+ "lastDate": { "year": 2025, "month": 10, "day": 26 }
+ },
+ ...
+ ]
+ }
+}
+```
+
+### NaN Handling
+- `"NaN"` string for densities in ineligible periods
+- `null` for percentile values in ineligible periods
+- Always check for these before numeric operations
+
+### Update Schedule
+- Updated **Mondays** ~04:00 UTC
+- Each period = 28-day rolling average ending on a Sunday
+
+---
+
+## Core Web Vitals Thresholds
+
+Current as of March 2026. INP replaced FID on March 12, 2024.
+
+| Metric | Good | Needs Improvement | Poor |
+|--------|------|-------------------|------|
+| **LCP** | ≤ 2,500ms | 2,500–4,000ms | > 4,000ms |
+| **INP** | ≤ 200ms | 200–500ms | > 500ms |
+| **CLS** | ≤ 0.1 | 0.1–0.25 | > 0.25 |
+| **FCP** | ≤ 1,800ms | 1,800–3,000ms | > 3,000ms |
+| **TTFB** | ≤ 800ms | 800–1,800ms | > 1,800ms |
+
+FID was fully removed from Chrome tools (CrUX, PSI, Lighthouse) on September 9, 2024. Never reference FID in outputs.
diff --git a/skills/seo-google/references/rate-limits-quotas.md b/skills/seo-google/references/rate-limits-quotas.md
new file mode 100644
index 0000000..dc6b6da
--- /dev/null
+++ b/skills/seo-google/references/rate-limits-quotas.md
@@ -0,0 +1,75 @@
+# Google API Rate Limits & Quotas
+
+## Consolidated Quota Table
+
+| API | Per-Minute | Per-Day | Cost | Auth Type | Scope |
+|-----|-----------|---------|------|-----------|-------|
+| GSC Search Analytics | 1,200 QPM/user, 1,200 QPM/site | 30M QPD/project | Free | Service Account | Per user + per site |
+| GSC URL Inspection | 600 QPM/site | 2,000 QPD/site | Free | Service Account | Per site |
+| GSC Sitemaps | Standard | Standard | Free | Service Account | Per site |
+| PageSpeed Insights v5 | 240 QPM | 25,000 QPD | Free | API Key | Per project |
+| CrUX API | 150 QPM (shared) | Unlimited | Free | API Key | Per project |
+| CrUX History API | 150 QPM (shared with CrUX) | Unlimited | Free | API Key | Per project |
+| Indexing API | 380 RPM total, 180 read/min | 200 publish/day | Free | Service Account | Per project |
+| GA4 Data API | 10 concurrent | ~25K tokens/day | Free | Service Account | Per property/project |
+| Knowledge Graph | -- | 100,000 QPD | Free | API Key | Per project |
+| Custom Search | -- | 10,000 QPD max | 100 free, $5/1K | API Key | Per project |
+| Web Risk | 6,000 QPM | 100K/month | Free tier | API Key | Per project |
+
+**Key distinction:** "Per site" quotas are scoped to a specific GSC property. "Per project" quotas are shared across all properties in a GCP project. "Per user" quotas are per authenticated user (service account).
+
+## Exponential Backoff Strategy
+
+When receiving 429 or 5xx errors:
+
+```
+Attempt 1: wait 1 second
+Attempt 2: wait 2 seconds
+Attempt 3: wait 4 seconds
+Attempt 4: wait 8 seconds
+Attempt 5: wait 16 seconds
+Max: give up after 5 retries
+```
+
+Add random jitter (0-500ms) to each wait to avoid thundering herd.
+
+## Common Error Codes
+
+| Code | Meaning | Applies To | Action |
+|------|---------|------------|--------|
+| 400 | Bad request | All | Check URL format, request body |
+| 401 | Unauthorized | Service Account APIs | Refresh credentials |
+| 403 | Forbidden | GSC, GA4, Indexing | Check permissions (service account access) |
+| 404 | Not found | CrUX, GSC | Insufficient traffic (CrUX) or invalid property (GSC) |
+| 429 | Rate limited | All | Backoff and retry. Check Retry-After header. |
+| 500 | Server error | All | Retry with backoff |
+| 503 | Service unavailable | All | Retry with backoff |
+
+## Retry-After Header
+
+Some Google APIs return a `Retry-After` header with 429 responses. When present, use this value (in seconds) instead of exponential backoff.
+
+## GA4 Token Budgeting
+
+GA4 uses a token system rather than simple request counts:
+- Simple 1-dimension, 1-metric report: ~1-5 tokens
+- Complex multi-dimension, multi-metric: ~10-100 tokens
+- Set `returnPropertyQuota: true` to monitor consumption
+- Daily limit: 25,000 tokens per property per project
+- Hourly limit: 5,000 tokens per property per project
+- Concurrent: max 10 simultaneous requests
+
+## CrUX Shared Quota
+
+The CrUX API and CrUX History API share the same 150 QPM quota per project. Plan accordingly if querying both APIs in the same workflow.
+
+## Cost Summary
+
+**All APIs used by seo-google are free** at normal usage levels. No billing is required for:
+- PSI, CrUX, CrUX History (API key, unlimited free)
+- GSC (service account, 30M QPD)
+- Indexing API (service account, 200 publish/day)
+- GA4 Data API (service account, 25K tokens/day)
+- Knowledge Graph (API key, 100K QPD)
+
+Only Custom Search and Web Risk have paid tiers at high volumes.
diff --git a/skills/seo-google/references/search-console-api.md b/skills/seo-google/references/search-console-api.md
new file mode 100644
index 0000000..59eb0f7
--- /dev/null
+++ b/skills/seo-google/references/search-console-api.md
@@ -0,0 +1,156 @@
+# Google Search Console API Reference
+
+## Table of Contents
+1. [Search Analytics API](#search-analytics-api)
+2. [URL Inspection API](#url-inspection-api)
+3. [Sitemaps API](#sitemaps-api)
+4. [Sites API](#sites-api)
+
+---
+
+## Search Analytics API
+
+**Endpoint:** `POST https://www.googleapis.com/webmasters/v3/sites/{siteUrl}/searchAnalytics/query`
+
+### Request Body
+
+| Field | Type | Description |
+|-------|------|-------------|
+| `startDate` | string | Required. YYYY-MM-DD format. |
+| `endDate` | string | Required. YYYY-MM-DD format. |
+| `dimensions` | string[] | `query`, `page`, `country`, `device`, `date`, `searchAppearance` |
+| `type` | string | `web` (default), `image`, `video`, `news`, `discover`, `googleNews` |
+| `dimensionFilterGroups` | object[] | Array of filter groups (see below) |
+| `aggregationType` | string | `auto` (default), `byPage`, `byProperty`, `byNewsShowcasePanel` |
+| `rowLimit` | int | 1-25000 (default: 1000) |
+| `startRow` | int | Pagination offset (default: 0) |
+| `dataState` | string | `final` (default), `all`, `hourly_all` |
+
+### Dimension Filters
+
+```json
+{
+ "dimensionFilterGroups": [{
+ "filters": [{
+ "dimension": "query",
+ "operator": "contains",
+ "expression": "seo"
+ }]
+ }]
+}
+```
+
+**Operators:** `contains`, `equals`, `notContains`, `notEquals`, `includingRegex`, `excludingRegex`
+- Regex uses RE2 syntax, max 4096 characters
+
+### Response
+
+```json
+{
+ "rows": [
+ {
+ "keys": ["seo tools", "https://example.com/tools"],
+ "clicks": 150,
+ "impressions": 5000,
+ "ctr": 0.03,
+ "position": 4.2
+ }
+ ],
+ "responseAggregationType": "byPage"
+}
+```
+
+### Important Notes
+- Data has a **2-3 day lag**. Available for approximately 16 months.
+- `discover` and `googleNews` types do not support `query` dimension or `position` metric.
+- Country codes are **ISO 3166-1 alpha-3** (e.g., `USA`, `GBR`, `DEU`).
+- Pagination: increment `startRow` by `rowLimit` until fewer rows returned.
+
+### Rate Limits
+- 1,200 QPM per user
+- 1,200 QPM per site
+- 40,000 QPM / 30,000,000 QPD per project
+
+---
+
+## URL Inspection API
+
+**Endpoint:** `POST https://searchconsole.googleapis.com/v1/urlInspection/index:inspect`
+
+### Request
+
+```json
+{
+ "inspectionUrl": "https://example.com/page",
+ "siteUrl": "sc-domain:example.com",
+ "languageCode": "en"
+}
+```
+
+### Response Fields
+
+**`indexStatusResult`:**
+
+| Field | Values |
+|-------|--------|
+| `verdict` | `PASS`, `FAIL`, `NEUTRAL`, `PARTIAL`, `VERDICT_UNSPECIFIED` |
+| `coverageState` | Human-readable coverage description |
+| `robotsTxtState` | `ALLOWED`, `DISALLOWED` |
+| `indexingState` | `INDEXING_ALLOWED`, `BLOCKED_BY_META_TAG`, `BLOCKED_BY_HTTP_HEADER` |
+| `pageFetchState` | `SUCCESSFUL`, `SOFT_404`, `BLOCKED_ROBOTS_TXT`, `NOT_FOUND`, `ACCESS_DENIED`, `SERVER_ERROR`, `REDIRECT_ERROR`, `ACCESS_FORBIDDEN`, `BLOCKED_4XX`, `INTERNAL_CRAWL_ERROR`, `INVALID_URL` |
+| `lastCrawlTime` | ISO 8601 timestamp |
+| `googleCanonical` | URL Google selected as canonical |
+| `userCanonical` | URL declared canonical by the page |
+| `crawledAs` | `DESKTOP`, `MOBILE` |
+
+**`richResultsResult`:** Verdict + detected rich result types (FAQPage, HowTo, etc.)
+
+### Rate Limits
+- 2,000 QPD / 600 QPM per site
+- 10,000,000 QPD / 15,000 QPM per project
+
+---
+
+## Sitemaps API
+
+**Base:** `https://www.googleapis.com/webmasters/v3/sites/{siteUrl}/sitemaps`
+
+| Method | Endpoint | Description |
+|--------|----------|-------------|
+| `GET` | `/sitemaps` | List all sitemaps |
+| `GET` | `/sitemaps/{feedpath}` | Get specific sitemap |
+| `PUT` | `/sitemaps/{feedpath}` | Submit a sitemap |
+| `DELETE` | `/sitemaps/{feedpath}` | Delete a sitemap |
+
+### Sitemap Resource
+
+| Field | Description |
+|-------|-------------|
+| `path` | URL of the sitemap |
+| `lastSubmitted` | Last submission timestamp |
+| `isPending` | Whether processing is incomplete |
+| `isSitemapsIndex` | Whether this is a sitemap index |
+| `type` | `sitemap`, `atomFeed`, `rssFeed`, `urlList`, `notSitemap` |
+| `warnings` | Warning count |
+| `errors` | Error count |
+| `contents[]` | Array with `type` (web, image, video, news) and `submitted` count |
+
+---
+
+## Sites API
+
+**Base:** `https://www.googleapis.com/webmasters/v3/sites`
+
+| Method | Endpoint | Description |
+|--------|----------|-------------|
+| `GET` | `/sites` | List all verified properties |
+| `GET` | `/sites/{siteUrl}` | Get property info |
+| `PUT` | `/sites/{siteUrl}` | Add a property |
+| `DELETE` | `/sites/{siteUrl}` | Remove a property |
+
+### Property Resource
+
+| Field | Values |
+|-------|--------|
+| `siteUrl` | Property URL (e.g., `sc-domain:example.com`) |
+| `permissionLevel` | `siteOwner`, `siteFullUser`, `siteRestrictedUser`, `siteUnverifiedUser` |
diff --git a/skills/seo-google/references/supplementary-apis.md b/skills/seo-google/references/supplementary-apis.md
new file mode 100644
index 0000000..2662f4b
--- /dev/null
+++ b/skills/seo-google/references/supplementary-apis.md
@@ -0,0 +1,99 @@
+# Supplementary Google APIs for SEO
+
+## Knowledge Graph Search API
+
+Verify brand/entity presence in Google's Knowledge Graph.
+
+**Endpoint:** `GET https://kgsearch.googleapis.com/v1/entities:search`
+
+| Param | Description |
+|-------|-------------|
+| `query` | Search query |
+| `ids` | Specific entity IDs (e.g., `/m/0d6lp`) |
+| `languages` | Language codes (e.g., `en`) |
+| `types` | Schema.org types to filter (e.g., `Organization`, `Person`) |
+| `limit` | Max results (1-500) |
+| `key` | API key (required) |
+
+**Response:**
+```json
+{
+ "itemListElement": [{
+ "result": {
+ "@id": "kg:/m/0d6lp",
+ "name": "Google",
+ "@type": ["Organization", "Corporation"],
+ "description": "Technology company",
+ "detailedDescription": {
+ "articleBody": "Google LLC is an American...",
+ "url": "https://en.wikipedia.org/wiki/Google"
+ },
+ "image": { "url": "..." },
+ "url": "https://www.google.com"
+ },
+ "resultScore": 4892.5
+ }]
+}
+```
+
+**Use for SEO:** Verify if a brand has a Knowledge Panel, check entity disambiguation, find related entities.
+
+**Quota:** 100,000 reads/day. Free. API key only.
+
+---
+
+## Custom Search JSON API
+
+Programmatic Google search results (limited).
+
+**Endpoint:** `GET https://customsearch.googleapis.com/customsearch/v1`
+
+| Param | Description |
+|-------|-------------|
+| `key` | API key (required) |
+| `cx` | Programmable Search Engine ID (required) |
+| `q` | Search query |
+| `num` | Results per page (1-10) |
+| `start` | Start index (max 91) |
+| `dateRestrict` | Date restriction (e.g., `d30` for 30 days) |
+| `gl` | Country (e.g., `us`) |
+| `lr` | Language restriction |
+| `searchType` | `image` for image search |
+| `siteSearch` | Restrict to a domain |
+
+**Limitations:**
+- Max 100 total results per query (10 pages x 10 results)
+- **CLOSED to new customers as of 2025.** Existing customers must migrate by January 2027.
+- 100 queries/day free, $5 per 1,000 up to 10,000/day
+
+**For SERP data, prefer DataForSEO** (`/seo dataforseo serp`) which has no such limitations.
+
+---
+
+## Web Risk API
+
+Check if URLs are flagged as unsafe by Google Safe Browsing.
+
+**Endpoint:** `GET https://webrisk.googleapis.com/v1/uris:search`
+
+| Param | Description |
+|-------|-------------|
+| `threatTypes` | `MALWARE`, `SOCIAL_ENGINEERING`, `UNWANTED_SOFTWARE`, `SOCIAL_ENGINEERING_EXTENDED_COVERAGE` |
+| `uri` | URL to check |
+| `key` | API key (required) |
+
+**Response (clean URL):** Empty threat object.
+
+**Response (flagged URL):**
+```json
+{
+ "threat": {
+ "threatTypes": ["MALWARE"],
+ "expireTime": "2026-04-01T00:00:00Z"
+ }
+}
+```
+
+**Use for SEO:** Check if pages are flagged (could explain deindexing), verify competitor safety, audit outbound links.
+
+**Quota:** 6,000 QPM. 100,000/month free tier. Requires billing enabled on GCP project.
diff --git a/skills/seo-google/references/youtube-api.md b/skills/seo-google/references/youtube-api.md
new file mode 100644
index 0000000..5d29fee
--- /dev/null
+++ b/skills/seo-google/references/youtube-api.md
@@ -0,0 +1,49 @@
+# YouTube Data API v3 Reference
+
+YouTube mentions have the strongest correlation with AI visibility (0.737 per GEO research). This API provides authoritative YouTube data directly from Google.
+
+## Endpoints Used
+
+| Method | Quota Cost | Description |
+|--------|-----------|-------------|
+| `search.list` | 100 units | Search for videos matching a query |
+| `videos.list` | 1 unit | Get video details, statistics, content |
+| `channels.list` | 1 unit | Get channel info, subscriber count |
+| `commentThreads.list` | 1 unit | Get top comments on a video |
+
+## Daily Quota
+
+Default: **10,000 units/day** (free). This allows:
+- ~100 searches per day, OR
+- ~10,000 video/channel lookups per day
+
+## Data Available
+
+### Video Search
+- Title, channel, channel ID, published date
+- Description (first 300 chars), thumbnail URL
+- Views, likes, comments count, duration
+
+### Video Details
+- Full description, tags, category ID
+- Duration, definition (HD/SD), has captions
+- Topic categories (Wikipedia URLs)
+- Views, likes, comments, favorites
+- Top 10 relevant comments with likes
+
+### Channel Info
+- Title, description, custom URL
+- Subscriber count, video count, total views
+- Country, published date, thumbnail
+
+## Authentication
+
+**API key only** (read-only public data). No OAuth needed.
+
+## Enable the API
+
+1. Go to [console.cloud.google.com/apis/library](https://console.cloud.google.com/apis/library)
+2. Search for "YouTube Data API v3"
+3. Click Enable
+
+No billing required. The API key you already have for PSI/CrUX works.
diff --git a/skills/seo-hreflang/SKILL.md b/skills/seo-hreflang/SKILL.md
index be83d72..f821aea 100644
--- a/skills/seo-hreflang/SKILL.md
+++ b/skills/seo-hreflang/SKILL.md
@@ -11,7 +11,7 @@ license: MIT
allowed-tools: Read, Grep, Glob, Bash, WebFetch
metadata:
author: AgriciDaniel
- version: "1.6.1"
+ version: "1.7.0"
category: seo
---
diff --git a/skills/seo-image-gen/SKILL.md b/skills/seo-image-gen/SKILL.md
index 8943f43..f52272e 100644
--- a/skills/seo-image-gen/SKILL.md
+++ b/skills/seo-image-gen/SKILL.md
@@ -8,7 +8,7 @@ allowed-tools: Read, Grep, Glob, Bash, WebFetch, Write
compatibility: "Requires nanobanana MCP server"
metadata:
author: AgriciDaniel
- version: "1.6.1"
+ version: "1.7.0"
category: seo
---
diff --git a/skills/seo-images/SKILL.md b/skills/seo-images/SKILL.md
index 918905d..06a9300 100644
--- a/skills/seo-images/SKILL.md
+++ b/skills/seo-images/SKILL.md
@@ -11,7 +11,7 @@ license: MIT
allowed-tools: Read, Grep, Glob, Bash, WebFetch
metadata:
author: AgriciDaniel
- version: "1.6.1"
+ version: "1.7.0"
category: seo
---
diff --git a/skills/seo-local/SKILL.md b/skills/seo-local/SKILL.md
index 0770b48..edbfd5f 100644
--- a/skills/seo-local/SKILL.md
+++ b/skills/seo-local/SKILL.md
@@ -16,7 +16,7 @@ license: MIT
allowed-tools: Read, Grep, Glob, Bash, WebFetch, Write
metadata:
author: AgriciDaniel
- version: "1.6.1"
+ version: "1.7.0"
category: seo
---
diff --git a/skills/seo-maps/SKILL.md b/skills/seo-maps/SKILL.md
index 5305760..1b37e4b 100644
--- a/skills/seo-maps/SKILL.md
+++ b/skills/seo-maps/SKILL.md
@@ -17,7 +17,7 @@ allowed-tools: Read, Grep, Glob, Bash, WebFetch, Write
compatibility: "DataForSEO MCP for Tier 1+, Google Maps API for Tier 2"
metadata:
author: AgriciDaniel
- version: "1.6.1"
+ version: "1.7.0"
category: seo
---
diff --git a/skills/seo-page/SKILL.md b/skills/seo-page/SKILL.md
index a2c981f..3f34b2c 100644
--- a/skills/seo-page/SKILL.md
+++ b/skills/seo-page/SKILL.md
@@ -11,7 +11,7 @@ license: MIT
allowed-tools: Read, Grep, Glob, Bash, WebFetch
metadata:
author: AgriciDaniel
- version: "1.6.1"
+ version: "1.7.0"
category: seo
---
diff --git a/skills/seo-plan/SKILL.md b/skills/seo-plan/SKILL.md
index a2e0b5b..b6c383d 100644
--- a/skills/seo-plan/SKILL.md
+++ b/skills/seo-plan/SKILL.md
@@ -12,7 +12,7 @@ license: MIT
allowed-tools: Read, Grep, Glob, Bash, WebFetch, Write
metadata:
author: AgriciDaniel
- version: "1.6.1"
+ version: "1.7.0"
category: seo
---
diff --git a/skills/seo-programmatic/SKILL.md b/skills/seo-programmatic/SKILL.md
index 1354214..492da84 100644
--- a/skills/seo-programmatic/SKILL.md
+++ b/skills/seo-programmatic/SKILL.md
@@ -12,7 +12,7 @@ license: MIT
allowed-tools: Read, Grep, Glob, Bash, WebFetch, Write
metadata:
author: AgriciDaniel
- version: "1.6.1"
+ version: "1.7.0"
category: seo
---
diff --git a/skills/seo-schema/SKILL.md b/skills/seo-schema/SKILL.md
index 64f86df..18a9ffb 100644
--- a/skills/seo-schema/SKILL.md
+++ b/skills/seo-schema/SKILL.md
@@ -10,7 +10,7 @@ license: MIT
allowed-tools: Read, Grep, Glob, Bash, WebFetch, Write
metadata:
author: AgriciDaniel
- version: "1.6.1"
+ version: "1.7.0"
category: seo
---
diff --git a/skills/seo-sitemap/SKILL.md b/skills/seo-sitemap/SKILL.md
index 4a4f375..9ac1e7a 100644
--- a/skills/seo-sitemap/SKILL.md
+++ b/skills/seo-sitemap/SKILL.md
@@ -10,7 +10,7 @@ license: MIT
allowed-tools: Read, Grep, Glob, Bash, WebFetch, Write
metadata:
author: AgriciDaniel
- version: "1.6.1"
+ version: "1.7.0"
category: seo
---
diff --git a/skills/seo-technical/SKILL.md b/skills/seo-technical/SKILL.md
index 046ab3a..fb04632 100644
--- a/skills/seo-technical/SKILL.md
+++ b/skills/seo-technical/SKILL.md
@@ -11,7 +11,7 @@ license: MIT
allowed-tools: Read, Grep, Glob, Bash, WebFetch
metadata:
author: AgriciDaniel
- version: "1.6.1"
+ version: "1.7.0"
category: seo
---
@@ -160,6 +160,10 @@ Google updated its JavaScript SEO documentation in December 2025 with critical c
If DataForSEO MCP tools are available, use `on_page_instant_pages` for real page analysis (status codes, page timing, broken links, on-page checks), `on_page_lighthouse` for Lighthouse audits (performance, accessibility, SEO scores), and `domain_analytics_technologies_domain_technologies` for technology stack detection.
+## Google API Integration (Optional)
+
+If Google API credentials are configured, use `python scripts/pagespeed_check.py <url> --json` for real PSI + CrUX field data (replaces lab-only CWV estimates), `python scripts/crux_history.py <url> --json` for 25-week CWV trends, and `python scripts/gsc_inspect.py <url> --json` for real indexation status per URL.
+
## Error Handling
| Scenario | Action |
diff --git a/skills/seo/SKILL.md b/skills/seo/SKILL.md
index c1ff8e4..c2c2df1 100644
--- a/skills/seo/SKILL.md
+++ b/skills/seo/SKILL.md
@@ -18,7 +18,7 @@ license: MIT
allowed-tools: Read, Grep, Glob, Bash, WebFetch, Agent
metadata:
author: AgriciDaniel
- version: "1.6.1"
+ version: "1.7.0"
category: seo
---
@@ -29,7 +29,7 @@ metadata:
**Scripts:** Located at the plugin root `scripts/` directory.
Comprehensive SEO analysis across all industries (SaaS, local services,
-e-commerce, publishers, agencies). Orchestrates 14 specialized sub-skills and 9 subagents
+e-commerce, publishers, agencies). Orchestrates 15 specialized sub-skills and 10 subagents
(+ 2 optional extension sub-skills: seo-dataforseo and seo-image-gen).
## Quick Reference
@@ -50,6 +50,7 @@ e-commerce, publishers, agencies). Orchestrates 14 specialized sub-skills and 9
| `/seo local <url>` | Local SEO analysis (GBP, citations, reviews, map pack) |
| `/seo maps [command] [args]` | Maps intelligence (geo-grid, GBP audit, reviews, competitors) |
| `/seo hreflang [url]` | Hreflang/i18n SEO audit and generation |
+| `/seo google [command] [url]` | Google SEO APIs (GSC, PageSpeed, CrUX, Indexing, GA4) |
| `/seo dataforseo [command]` | Live SEO data via DataForSEO (extension) |
| `/seo image-gen [use-case] <description>` | AI image generation for SEO assets (extension) |
@@ -58,12 +59,15 @@ e-commerce, publishers, agencies). Orchestrates 14 specialized sub-skills and 9
When the user invokes `/seo audit`, delegate to subagents in parallel:
1. Detect business type (SaaS, local, ecommerce, publisher, agency, other)
2. Spawn subagents: seo-technical, seo-content, seo-schema, seo-sitemap, seo-performance, seo-visual, seo-geo
-3. If local business detected, also spawn seo-local agent
-4. If local business detected AND DataForSEO MCP available, also spawn seo-maps agent
-5. Collect results and generate unified report with SEO Health Score (0-100)
-6. Create prioritized action plan (Critical -> High -> Medium -> Low)
+3. If Google API credentials detected (`python scripts/google_auth.py --check`), also spawn seo-google agent
+4. If local business detected, also spawn seo-local agent
+5. If local business detected AND DataForSEO MCP available, also spawn seo-maps agent
+6. Collect results and generate unified report with SEO Health Score (0-100)
+7. Create prioritized action plan (Critical -> High -> Medium -> Low)
+8. **Offer PDF report**: "Generate a professional PDF report? Use `/seo google report full`"
For individual commands, load the relevant sub-skill directly.
+After any analysis command completes, offer to generate a PDF report via `scripts/google_report.py`.
## Industry Detection
@@ -120,7 +124,7 @@ Weighted aggregate of all categories:
## Sub-Skills
-This skill orchestrates 14 specialized sub-skills (+ 2 extensions):
+This skill orchestrates 15 specialized sub-skills (+ 2 extensions):
1. **seo-audit** -- Full website audit with parallel delegation
2. **seo-page** -- Deep single-page analysis
@@ -136,8 +140,9 @@ This skill orchestrates 14 specialized sub-skills (+ 2 extensions):
12. **seo-hreflang** -- Hreflang/i18n SEO audit and generation
13. **seo-local** -- Local SEO (GBP, NAP, citations, reviews, local schema, multi-location)
14. **seo-maps** -- Maps intelligence (geo-grid, GBP audit, reviews, competitor radius)
-15. **seo-dataforseo** -- Live SEO data via DataForSEO MCP (extension)
-16. **seo-image-gen** -- AI image generation for SEO assets via Gemini (extension)
+15. **seo-google** -- Google SEO APIs (GSC, PageSpeed, CrUX, Indexing API, GA4)
+16. **seo-dataforseo** -- Live SEO data via DataForSEO MCP (extension)
+17. **seo-image-gen** -- AI image generation for SEO assets via Gemini (extension)
## Subagents
@@ -151,6 +156,7 @@ For parallel analysis during audits:
- `seo-geo` -- AI crawler access, llms.txt, citability, brand mention signals
- `seo-local` -- GBP signals, NAP consistency, reviews, local schema, industry-specific local factors (conditional: spawned when Local Service detected)
- `seo-maps` -- Geo-grid rank tracking, GBP audit, review intelligence, competitor radius mapping (conditional: spawned when Local Service detected AND DataForSEO MCP available)
+- `seo-google` -- CWV field data, URL indexation status, organic traffic trends (conditional: spawned when Google API credentials detected)
- `seo-dataforseo` -- Live SERP, keyword, backlink, local SEO data (extension, optional)
- `seo-image-gen` -- SEO image audit and generation plan (extension, optional)