"""
Script pour télécharger toutes les images du site WordPress
et récupérer la mise en page complète
"""

import requests
from bs4 import BeautifulSoup
import json
import os
from urllib.parse import urlparse, urljoin
import time

def download_image(url, save_path):
    """Télécharge une image depuis une URL"""
    try:
        response = requests.get(url, timeout=10)
        response.raise_for_status()
        
        # Créer le dossier si nécessaire
        os.makedirs(os.path.dirname(save_path), exist_ok=True)
        
        # Sauvegarder l'image
        with open(save_path, 'wb') as f:
            f.write(response.content)
        
        return True
    except Exception as e:
        print(f"    ❌ Erreur téléchargement {url}: {e}")
        return False

def get_page_structure(url):
    """Récupère la structure complète d'une page"""
    try:
        response = requests.get(url, timeout=10)
        soup = BeautifulSoup(response.content, 'html.parser')
        
        structure = {
            'url': url,
            'title': '',
            'sections': [],
            'images': [],
            'colors': {},
            'fonts': []
        }
        
        # Titre de la page
        title = soup.find('h1')
        if title:
            structure['title'] = title.get_text(strip=True)
        
        # Trouver toutes les sections principales
        main = soup.find('main') or soup.find('body')
        if main:
            # Parcourir les sections
            sections = main.find_all(['section', 'div'], class_=lambda x: x and any(keyword in str(x).lower() for keyword in ['section', 'content', 'block', 'widget']))
            
            for section in sections[:20]:  # Limiter à 20 sections
                section_data = {
                    'type': section.name,
                    'classes': section.get('class', []),
                    'headings': [],
                    'paragraphs': [],
                    'images': [],
                    'background_color': '',
                    'background_image': ''
                }
                
                # Récupérer les titres de la section
                for heading in section.find_all(['h1', 'h2', 'h3', 'h4', 'h5', 'h6']):
                    text = heading.get_text(strip=True)
                    if text:
                        section_data['headings'].append({
                            'level': heading.name,
                            'text': text
                        })
                
                # Récupérer les paragraphes
                for p in section.find_all('p'):
                    text = p.get_text(strip=True)
                    if text and len(text) > 10:
                        section_data['paragraphs'].append(text)
                
                # Récupérer les images de la section
                for img in section.find_all('img'):
                    src = img.get('src', '')
                    if src:
                        section_data['images'].append({
                            'src': src,
                            'alt': img.get('alt', ''),
                            'class': img.get('class', [])
                        })
                
                # Récupérer le style de fond
                style = section.get('style', '')
                if 'background' in style.lower():
                    section_data['background_color'] = style
                
                if section_data['headings'] or section_data['paragraphs'] or section_data['images']:
                    structure['sections'].append(section_data)
        
        # Récupérer toutes les images de la page
        for img in soup.find_all('img'):
            src = img.get('src', '')
            if src:
                structure['images'].append({
                    'src': src,
                    'alt': img.get('alt', ''),
                    'class': img.get('class', []),
                    'srcset': img.get('srcset', '')
                })
        
        return structure
    except Exception as e:
        print(f"  ❌ Erreur: {e}")
        return None

def main():
    print("=" * 70)
    print("TÉLÉCHARGEMENT DES IMAGES ET RÉCUPÉRATION DE LA MISE EN PAGE")
    print("=" * 70)
    
    # Créer le dossier pour les images
    images_dir = 'media/downloaded_images'
    os.makedirs(images_dir, exist_ok=True)
    
    # URLs à analyser
    urls = [
        "https://www.transport-transco86.fr/",
        "https://www.transport-transco86.fr/transports-exceptionnel-nouvelle-aquitaine.html",
        "https://www.transport-transco86.fr/entreprise-transport-exceptionnel-nouvelle-aquitaine.html",
        "https://www.transport-transco86.fr/nos-moyens.html",
        "https://www.transport-transco86.fr/transport-tp.html",
        "https://www.transport-transco86.fr/contact.html",
    ]
    
    all_structures = []
    all_images = {}
    
    for url in urls:
        print(f"\n📄 Analyse de: {url}")
        structure = get_page_structure(url)
        
        if structure:
            all_structures.append(structure)
            print(f"  ✅ {len(structure['sections'])} sections trouvées")
            print(f"  📸 {len(structure['images'])} images trouvées")
            
            # Télécharger les images
            for idx, img in enumerate(structure['images']):
                src = img['src']
                if src.startswith('//'):
                    src = 'https:' + src
                elif src.startswith('/'):
                    src = 'https://www.transport-transco86.fr' + src
                
                # Nom du fichier
                parsed = urlparse(src)
                filename = os.path.basename(parsed.path)
                
                if not filename:
                    filename = f'image_{idx}.jpg'
                
                # Chemin de sauvegarde
                save_path = os.path.join(images_dir, filename)
                
                # Télécharger si pas déjà fait
                if filename not in all_images and 'wp-content/uploads' in src:
                    print(f"    📥 Téléchargement: {filename}")
                    if download_image(src, save_path):
                        all_images[filename] = {
                            'url': src,
                            'local_path': save_path,
                            'alt': img['alt']
                        }
                        time.sleep(0.5)  # Pause pour ne pas surcharger le serveur
        
        time.sleep(1)
    
    # Sauvegarder la structure complète
    with open('transco86_layout_structure.json', 'w', encoding='utf-8') as f:
        json.dump(all_structures, f, ensure_ascii=False, indent=2)
    
    # Sauvegarder la liste des images
    with open('transco86_images_mapping.json', 'w', encoding='utf-8') as f:
        json.dump(all_images, f, ensure_ascii=False, indent=2)
    
    print("\n" + "=" * 70)
    print("✅ TÉLÉCHARGEMENT TERMINÉ")
    print("=" * 70)
    print(f"\n📊 Résumé:")
    print(f"  - {len(all_structures)} pages analysées")
    print(f"  - {len(all_images)} images téléchargées")
    print(f"  - Images sauvegardées dans: {images_dir}/")
    print(f"  - Structure sauvegardée dans: transco86_layout_structure.json")
    print(f"  - Mapping images: transco86_images_mapping.json")
    
    # Afficher quelques exemples de structure
    print("\n📐 Exemples de structure récupérée:")
    for struct in all_structures[:2]:
        print(f"\n🔹 Page: {struct['title'] or struct['url']}")
        for section in struct['sections'][:3]:
            if section['headings']:
                print(f"  - Section: {section['headings'][0]['text']}")
                if section['paragraphs']:
                    print(f"    Texte: {section['paragraphs'][0][:80]}...")

if __name__ == "__main__":
    main()
