# Implementacao Tecnica - SEO Report

## Workflow Tecnico

```mermaid
graph LR
    A[Input: URL] --> B{Site em GSC?}
    B -->|Sim| C[Recolher dados GSC]
    B -->|Nao| D[Skip GSC, aviso]

    C --> E[Lighthouse Desktop]
    D --> E

    E --> F[Lighthouse Mobile]
    F --> G[Core Web Vitals]
    G --> H[SEO Tools API]
    H --> I{Ahrefs habilitado?}

    I -->|Sim| J[Recolher DR/UR]
    I -->|Nao| K[Skip Ahrefs]

    J --> L[Processar dados]
    K --> L

    L --> M[Gerar relatorio Markdown]
    M --> N[Criar Google Doc]
    N --> O[Partilhar com email]

    O --> P[Retornar link]
```

## Implementacao

```javascript
async function generateSEOReport(url, options = {}) {
  const {
    email = 'emanuelalmeidaa@gmail.com',
    competitors = [],
    includeAhrefs = true
  } = options;

  // 1. Validar URL
  if (!isValidURL(url)) {
    throw new Error('URL invalido');
  }

  // 2. Recolher dados em paralelo (melhor performance)
  const [
    lighthouseDesktop,
    lighthouseMobile,
    coreWebVitals,
    seoToolsData,
    gscData,
    ahrefsData
  ] = await Promise.allSettled([
    mcp__lighthouse__run_audit(url, 'desktop'),
    mcp__lighthouse__run_audit(url, 'mobile'),
    mcp__lighthouse__get_core_web_vitals(url),
    fetch(`http://localhost:3000/seo-audit?url=${url}`).then(r => r.json()),
    getGSCData(url),
    includeAhrefs ? getAhrefsData(url) : null
  ]);

  // 3. Processar e formatar
  const reportData = {
    url,
    date: new Date().toISOString().split('T')[0],
    scores: extractScores(lighthouseDesktop, lighthouseMobile),
    cwv: processCoreWebVitals(coreWebVitals),
    gsc: processGSCData(gscData),
    onPage: processOnPageData(seoToolsData),
    backlinks: processBacklinks(ahrefsData),
    recommendations: generateRecommendations(/* all data */)
  };

  // 4. Gerar documento Markdown
  const markdown = generateReportMarkdown(reportData);

  // 5. Criar Google Doc
  const docResult = await mcp__google-workspace__create_doc({
    title: `Relatorio SEO - ${extractDomain(url)} - ${reportData.date}`,
    body_content: markdown,
    user_google_email: email
  });

  // 6. Retornar link
  return {
    success: true,
    doc_url: docResult.url,
    summary: reportData.recommendations.slice(0, 5)
  };
}
```

## Propriedades GSC Disponiveis

```javascript
const GSC_PROPERTIES = [
  'sc-domain:descomplicar.pt',
  'https://emanuelalmeida.pt/',
  'https://carstuff.pt/',
  'https://solarfvengenharia.com/',
  'https://aquisevende.pt/',
  'https://alojadamaria.com/',
  'https://e-commerce.descomplicar.pt/'
];

async function getGSCData(url) {
  const domain = extractDomain(url);
  const property = GSC_PROPERTIES.find(p => p.includes(domain));

  if (!property) {
    console.warn(`Site ${domain} nao esta no GSC. Dados GSC nao disponiveis.`);
    return null;
  }

  const analytics = await mcp__gsc__get_search_analytics({
    site_url: property,
    start_date: daysAgo(90),
    end_date: 'today',
    dimensions: ['query'],
    row_limit: 100
  });

  return analytics;
}
```

## Notas Tecnicas

### Requisitos
- SEO Tools API a correr: `~/mcp-servers/seo-tools-api/start.sh`
- Google Workspace MCP configurado
- GSC authentication (OAuth primeira vez)

### Performance
- Execucao paralela de tools (1m40s total)
- Cache Lighthouse results (5 min TTL)
- Rate limiting Ahrefs API (100 req/day free)

### Erros Comuns
- **Site nao em GSC:** Relatorio gerado sem dados GSC
- **Lighthouse timeout:** Retry automatico (3x)
- **Ahrefs rate limit:** Skip backlinks, aviso no relatorio
