# SEO, AEO & GEO Management Tool — Architecture & Implementation Plan

## 1. Project Overview
A centralized, **implementation-first** SEO, AEO (Answer Engine Optimization), and GEO (Generative Engine Optimization) management platform built for **20+ WordPress websites** (hosted on Kinsta, Hostinger, and cPanel).

Unlike traditional audit tools that stop at listing problems, this system closes the loop:
1. **Scan & Collect** — Crawl pages + pull Google Search Console (GSC), GA4, and PageSpeed Insights data.
2. **AI-Powered Suggestions** — Feed the complete data bundle to an LLM to generate specific, ready-to-apply SEO/AEO/GEO improvements (replacing slow manual ChatGPT workflows).
3. **Prioritized Task Queue (`High` / `Medium` / `Low`)** — Rank tasks by issue severity × real page traffic/impression impact.
4. **Implement & Verify** — Track implementation status and automatically re-fetch live URLs to confirm fixes are actually live (and remain live).

---

## 2. Recommended Tech Stack

**Choice: TypeScript Full-Stack (`Next.js App Router` + `MySQL` + `Redis / BullMQ`)**

### Why TypeScript/Next.js over Python (FastAPI) + React
* **Single Codebase & Shared Types:** One language across the UI, API routes, background workers, and database. Using **Zod**, the exact same schema validates the AI's structured JSON output, saves it to MySQL, and renders it in the UI.
* **Best-in-Class Scraping & DOM Tooling:** `cheerio` (fast HTML parsing) + `playwright` (when JS rendering is needed) + `turndown` (clean HTML-to-Markdown for LLM prompts) are mature and fast in Node.js.
* **Simpler Deployment:** Runs cleanly via Docker Compose (`app`, `worker`, `mysql`, `redis`) or directly against the MySQL instance already installed on your Hostinger/cPanel/VPS servers.

### Core Stack Components
* **Frontend / API:** Next.js (App Router), TypeScript, Tailwind CSS, shadcn/ui
* **Database & ORM:** MySQL 8+ / MariaDB + Drizzle ORM (`mysql2`)
* **Background Jobs:** BullMQ + Redis (scheduled crawls, GSC/GA4 sync, AI batch audits, verification checks)
* **Crawler & Parser:** `fetch` + `cheerio` (primary), `playwright` (fallback for JS-heavy checks), `turndown` (HTML → Markdown)
* **AI Layer:** Pluggable LLM provider (Gemini / OpenAI) with **Structured JSON Output** (Zod-validated)
* **Google APIs:** `googleapis` (Search Console API, Analytics Data API GA4, PageSpeed Insights API)

---

## 3. WordPress Stack Integration (SEOPress + WP Rocket + Code Snippets)

All 20+ sites share a consistent WordPress stack, which unlocks major automation advantages:

### A. WordPress REST API + Application Passwords
* Built into WordPress core across Kinsta, Hostinger, and cPanel.
* Allows the tool to fetch the exact post/page inventory, published dates, categories, and slugs without hammering the server with blind discovery crawls.

### B. SEOPress Integration
* Read and audit SEOPress metadata (`_seopress_titles_title`, `_seopress_titles_desc`, `_seopress_robots_canonical`, `_seopress_robots_index`, schema settings).
* **Phase 2 (1-Click Push):** Expose SEOPress meta fields via a lightweight PHP snippet (deployed via **Code Snippets**) so approved title/meta/schema updates can be pushed directly from the dashboard as a safe revision.

### C. WP Rocket Cache Handling
* Aggressive page caching can make newly implemented changes appear "missing" to a naive crawler.
* **Verification Strategy:**
  * Use cache-busting parameters (e.g., `?nowprocket` when testing uncached origin output vs. normal URL to verify what visitors/bots see).
  * Optionally trigger WP Rocket cache purge on a specific URL via a small Code Snippets REST endpoint after pushing an update.

### D. Code Snippets Advantage
* Because all sites use the **Code Snippets** plugin, we can maintain a single, optional **25-line companion snippet** for sites where you want 1-click implementation (exposing SEOPress meta updates, triggering WP Rocket URL purge, or injecting validated JSON-LD / `llms.txt`).

---

## 4. Data Sources & DataForSEO Evaluation

### Free / Owned Data (Core — Used from Day 1)
| Source | Purpose | Cost |
| :--- | :--- | :--- |
| **Custom Crawler** | On-page HTML, headings, schema, links, `robots.txt`, `llms.txt`, and **implementation verification** | Free |
| **Google Search Console API** | Real queries, impressions, clicks, CTR, and avg position per URL (20+ sites) | Free |
| **Google Analytics (GA4) API** | Sessions, engagement, and conversions to weight task priority | Free |
| **PageSpeed Insights API** | Mobile/Desktop LCP, INP, CLS, and diagnostics (up to 25,000 req/day) | Free |

### DataForSEO (Optional Module — Phase 3)
* **Pricing Model:** Pay-as-you-go ($50 minimum deposit, credits never expire).
* **Not needed for crawling/PageSpeed:** Our own crawler + PageSpeed API are free and support custom verification rules.
* **Worth adding later for Rank & AI/GEO Tracking:**
  * **SERP API:** ~$0.60 per 1,000 SERPs (Standard async queue) — tracking 50 keywords/week across 20 sites (~4,000 SERPs/mo) costs **~$2.40/month**.
  * **AI Optimization API:** Track LLM mentions/citations (ChatGPT, Gemini, AI Overviews) without building proxy scrapers.

---

## 5. AI Audit & Suggestion Engine (Replacing Manual ChatGPT)

Instead of manually pasting URLs into ChatGPT, the worker builds a **Page Data Bundle** and runs a structured audit:

### Input Bundle per Page
1. **Clean Page Content:** Markdown of body text + `H1–H3` outline + word count.
2. **Technical & Meta:** Title, meta description, canonical, robots directives, existing JSON-LD schema, internal/external links, image alt-text gaps.
3. **GSC Context:** Top 20 queries for that URL (impressions, clicks, CTR, avg position).
4. **GA4 & CWV Context:** Traffic/conversion tier + LCP/INP/CLS scores.

### AI Output (Strict JSON Schema)
Each suggestion returned by the AI becomes an actionable task:
* **Pillar:** `SEO` | `AEO` | `GEO`
* **Issue Summary:** Concise explanation of *why* this matters based on the page's actual GSC/crawl data.
* **Suggested Change (Before → After):**
  * *SEO:* Rewritten Title/Meta targeting high-impression, low-CTR GSC queries; internal link anchor suggestions.
  * *AEO:* Question-based `H2/H3` rewrites, 40–60 word direct-answer summary blocks, and ready-to-paste `FAQPage` / `HowTo` JSON-LD.
  * *GEO:* Entity clarity, author/E-E-A-T signals, statistics/source citations, `llms.txt` & AI bot (`GPTBot`, `ClaudeBot`, `PerplexityBot`) crawlability checks.
* **Priority (`High` / `Medium` / `Low`):** Computed from AI severity × GSC/GA4 page importance.
* **Verification Rule:** Machine-checkable assertion (e.g., `title_contains`, `meta_desc_equals`, `schema_type_exists: FAQPage`, `text_snippet_present`, `status_code: 200`).

### Cost Optimization
* Use a fast, low-cost model (e.g., Gemini Flash / GPT-4o-mini) for initial page screening and routine checks.
* Use a stronger reasoning model for deep copy/AEO/GEO rewrites on **High-priority** pages.

---

## 6. High-Level Database Schema (MySQL)

* **`projects`** — `id`, `name`, `domain`, `wp_url`, `wp_username`, `wp_app_password_enc`, `gsc_property`, `ga4_property_id`, `crawl_schedule`, `created_at`
* **`pages`** — `id`, `project_id`, `url`, `wp_post_id`, `post_type`, `importance_score`, `last_crawled_at`
* **`crawl_snapshots`** — `id`, `page_id`, `status_code`, `title`, `meta_desc`, `canonical`, `h1`, `headings_json`, `schema_json`, `markdown_content`, `lcp_ms`, `cls`, `inp_ms`, `crawled_at`
* **`gsc_page_metrics`** — `id`, `page_id`, `date_range`, `clicks`, `impressions`, `ctr`, `avg_position`, `top_queries_json`, `synced_at`
* **`tasks`** — `id`, `project_id`, `page_id`, `pillar` (`SEO`/`AEO`/`GEO`), `priority` (`high`/`medium`/`low`), `status` (`open`/`in_progress`/`implemented`/`verified`/`failed`), `title`, `issue_detail`, `current_value`, `suggested_value`, `verification_rule_json`, `created_at`, `verified_at`
* **`verification_logs`** — `id`, `task_id`, `passed`, `observed_value`, `notes`, `checked_at`

---

## 7. Phased Implementation Roadmap

### Phase 1: MVP — Multi-Site Scanner, AI Suggestions & Verification Loop
* Project setup (Next.js, MySQL + Drizzle, Redis + BullMQ, Docker Compose).
* Project registry for 20+ WordPress sites (domain, GSC property, PageSpeed).
* Page crawler (`cheerio` + `turndown`) + GSC & PageSpeed Insights connectors.
* AI Audit Engine generating structured **SEO / AEO / GEO** tasks with **High / Medium / Low** priority and exact before/after suggestions.
* Task Dashboard (filter by project, priority, pillar, status) + **1-Click "Verify Implementation"** button that re-fetches the live URL and validates the fix.

### Phase 2: WordPress & SEOPress Deep Integration + GA4
* Connect WP REST API + Application Passwords for automatic page/post discovery.
* GA4 Data API integration for conversion-weighted priority scoring.
* Optional **Code Snippets** companion PHP snippet to read/update SEOPress meta fields and purge WP Rocket cache directly from the dashboard.

### Phase 3: Automated Monitoring & DataForSEO Rank/GEO Tracking
* Scheduled weekly re-crawls to detect regressions on previously verified tasks.
* Optional DataForSEO integration for SERP rank tracking and AI Overview / LLM citation monitoring.
