#!/usr/bin/env python3
"""
SuaVagAI — Fix Missing FAQ Schema
Generates FAQ schema for articles that don't have it using Claude API
Run: python3 /var/www/suavagai/bin/fix-missing-faq-schema.py
Criado: 2026-06-17
"""
import sqlite3, json, re, requests, time
from datetime import datetime

DB = '/var/www/suavagai/data/suavagai.db'
LOG = '/var/www/suavagai/data/artigo-seo.log'
TOKEN = ''  # CHAVE REMOVIDA 2026-08-19 - script desativado no cron

def log(msg):
    line = f'[{datetime.now().strftime("%Y-%m-%d %H:%M:%S")}] {msg}\n'
    print(msg)
    with open(LOG, 'a') as f:
        f.write(line)

def get_articles_without_faq(conn):
    cur = conn.cursor()
    cur.execute('''SELECT id, title, slug, substr(content, 1, 3000) 
                   FROM blog_posts 
                   WHERE published=1 AND (faq_schema IS NULL OR LENGTH(faq_schema)<10)
                   ORDER BY id DESC''')
    return cur.fetchall()

def extract_faqs_from_content(content):
    """Try to extract FAQs from content using multiple patterns"""
    faqs = []
    # Pattern 1: <h3>Q?</h3><p>A</p>
    for m in re.finditer(r'<h3[^>]*>(.*?)</h3>\s*<p>(.*?)</p>', content, re.DOTALL):
        q = re.sub(r'<[^>]+>', '', m.group(1)).strip()
        a = re.sub(r'<[^>]+>', '', m.group(2)).strip()[:300]
        if len(q) > 10 and len(a) > 20 and len(faqs) < 7:
            faqs.append({'q': q, 'a': a})
    return faqs

def generate_faqs_with_claude(title, content_excerpt):
    """Generate FAQs using Claude if extraction fails"""
    prompt = f'Com base no artigo "{title}", gere 5 perguntas frequentes (FAQ) com respostas.\n\nConteudo: {content_excerpt[:1500]}\n\nFORMATO (JSON array):\n[{{"q": "Pergunta 1?", "a": "Resposta 80-100 palavras."}}, ...]\n\nRetorne APENAS o JSON, sem markdown.'
    
    try:
        r = requests.post(
            'https://api.anthropic.com/v1/messages',
            headers={
                'x-api-key': TOKEN,
                'anthropic-version': '2023-06-01',
                'content-type': 'application/json'
            },
            json={
                'model': 'claude-haiku-3-5',
                'max_tokens': 800,
                'messages': [{'role': 'user', 'content': prompt}]
            },
            timeout=60
        )
        if r.status_code == 200:
            text = r.json()['content'][0]['text'].strip()
            # Clean markdown code blocks if present
            text = re.sub(r'^```(?:json)?\s*', '', text)
            text = re.sub(r'\s*```$', '', text)
            text = text.strip()
            faqs_data = json.loads(text)
            return [{'q': f['q'], 'a': f['a']} for f in faqs_data if 'q' in f and 'a' in f]
        else:
            log(f'  Claude HTTP {r.status_code}: {r.text[:100]}')
    except Exception as e:
        log(f'  Error: {e}')
    return None

def build_faq_schema(faqs):
    return json.dumps({
        '@context': 'https://schema.org',
        '@type': 'FAQPage',
        'mainEntity': [{
            '@type': 'Question',
            'name': f['q'],
            'acceptedAnswer': {
                '@type': 'Answer',
                'text': f['a']
            }
        } for f in faqs]
    })

def main():
    log('=== Fix Missing FAQ Schema iniciado ===')
    conn = sqlite3.connect(DB)
    articles = get_articles_without_faq(conn)
    log(f'Artigos sem FAQ schema: {len(articles)}')
    
    fixed = 0
    errors = 0
    
    for id_, title, slug, content_excerpt in articles:
        log(f'  Processando: {slug} (id={id_})')
        
        # Try extraction first (fast, no API)
        faqs = extract_faqs_from_content(content_excerpt)
        
        if not faqs:
            # Generate with Claude API
            log(f'  Gerando FAQs com Claude para: {title}')
            faqs = generate_faqs_with_claude(title, content_excerpt)
            time.sleep(2)  # Rate limit protection
        
        if faqs and len(faqs) >= 3:
            schema = build_faq_schema(faqs)
            cur = conn.cursor()
            cur.execute(
                "UPDATE blog_posts SET faq_schema=?, updated_at=datetime('now') WHERE id=?",
                (schema, id_)
            )
            conn.commit()
            log(f'  OK FAQ schema adicionado: {len(faqs)} perguntas')
            fixed += 1
        else:
            log(f'  AVISO sem FAQs para: {slug}')
            errors += 1
    
    conn.close()
    log(f'=== Concluido: {fixed} fixados, {errors} erros ===')

if __name__ == '__main__':
    main()
