# scraper.py
import sys
import logging
import requests
from config import WP_API_URL, LOG_FILE
from db import upsert_product, save_tags

logging.basicConfig(
    filename=LOG_FILE,
    level=logging.INFO,
    format='%(asctime)s %(levelname)s %(message)s'
)

HEADERS = {'User-Agent': 'CatalogueScraper/1.0'}

def get_all_products() -> list:
    products = []
    page = 1
    while True:
        resp = requests.get(
            WP_API_URL,
            params={'per_page': 100, 'page': page},
            headers=HEADERS,
            timeout=10
        )
        if resp.status_code != 200 or not resp.json():
            break
        products.extend(resp.json())
        page += 1
    return products

def process_product(wp_product: dict) -> bool:
    wp_post_id = wp_product.get('id')
    acf        = wp_product.get('acf', {})

    if not acf:
        logging.warning(f"Pas de champs ACF pour le post {wp_post_id}")
        return False

    data = {
        'wp_post_id':                  wp_post_id,
        'id_produit':                  acf.get('id_produit', ''),
        'url_produit':                 acf.get('url_produit', '') or wp_product.get('link', ''),
        'nom_produit':                 acf.get('nom_produit', ''),
        'categorie_produit_principale': acf.get('categorie_produit_principale', ''),
        'sous_categorie':              acf.get('sous_categorie', ''),
        'titre_1':                     acf.get('titre_1', ''),
        'description_1':               acf.get('description_1', ''),
        'bouton_1':                    acf.get('bouton_1', ''),
        'url_bouton_1':                acf.get('url_bouton_1', ''),
        'visuel_1':                    acf.get('visuel_1', ''),
        'url_visuel_1':                acf.get('url_visuel_1', ''),
        'titre_2':                     acf.get('titre_2', ''),
        'description_2':               acf.get('description_2', ''),
        'liste_a_puces_1':             acf.get('liste_a_puces_1', ''),
        'liste_a_puces_2':             acf.get('liste_a_puces_2', ''),
        'liste_a_puces_3':             acf.get('liste_a_puces_3', ''),
        'bouton_2':                    acf.get('bouton_2', ''),
        'url_bouton_2':                acf.get('url_bouton_2', ''),
        'visuel_2':                    acf.get('visuel_2', ''),
        'url_visuel_2':                acf.get('url_visuel_2', ''),
    }

    product_id = upsert_product(data)

    # Tags = catégorie principale + sous-catégorie
    tags = []
    if data['categorie_produit_principale']:
        tags.append(data['categorie_produit_principale'])
    if data['sous_categorie']:
        tags.append(data['sous_categorie'])
    save_tags(product_id, tags)

    logging.info(f"OK — {data['nom_produit']} (wp_id={wp_post_id})")
    return True

def scrape_all():
    products = get_all_products()
    logging.info(f"Scraping complet : {len(products)} produits")
    for p in products:
        process_product(p)

def scrape_single(wp_post_id: int):
    resp = requests.get(
        f"{WP_API_URL}/{wp_post_id}",
        headers=HEADERS,
        timeout=10
    )
    if resp.status_code == 200:
        process_product(resp.json())
    else:
        logging.error(f"Produit {wp_post_id} introuvable (HTTP {resp.status_code})")

if __name__ == '__main__':
    if len(sys.argv) == 3 and sys.argv[1] == '--single':
        scrape_single(int(sys.argv[2]))
    else:
        scrape_all()