#!/usr/bin/env python3
"""
Générateur de visualiseur HTML pour les pages Jobs.ch téléchargées
"""

import os
import json
import re
from pathlib import Path

def read_meta_file(meta_path):
    """Lit un fichier .meta et retourne les informations"""
    info = {}
    if meta_path.exists():
        with open(meta_path, 'r', encoding='utf-8') as f:
            for line in f:
                if ':' in line:
                    key, value = line.strip().split(':', 1)
                    info[key.strip()] = value.strip()
    return info

def extract_job_info(filename):
    """Extrait le type et l'ID du job depuis le nom du fichier"""
    # Pattern: type_id.html
    match = re.match(r'^(.+?)_(.+?)\.html$', filename)
    if match:
        return {
            'type': match.group(1),
            'id': match.group(2)
        }
    return {'type': 'unknown', 'id': filename.replace('.html', '')}

def generate_viewer_html(html_dir="html_pages", output_file="jobs_viewer.html"):
    """Génère le fichier HTML de visualisation"""
    
    html_path = Path(html_dir)
    if not html_path.exists():
        print(f"❌ Répertoire {html_dir} non trouvé")
        return False
    
    # Collecter tous les fichiers HTML
    files_data = []
    html_files = list(html_path.glob("*.html"))
    
    for html_file in html_files:
        meta_file = html_file.with_suffix('.meta')
        meta_info = read_meta_file(meta_file)
        job_info = extract_job_info(html_file.name)
        
        file_data = {
            'name': html_file.name,
            'type': job_info['type'],
            'id': job_info['id'],
            'url': meta_info.get('URL', ''),
            'date': meta_info.get('Date', ''),
            'status': meta_info.get('Status', ''),
            'size': html_file.stat().st_size if html_file.exists() else 0
        }
        files_data.append(file_data)
    
    # Trier par type puis par ID
    files_data.sort(key=lambda x: (x['type'], x['id']))
    
    print(f"📁 Trouvé {len(files_data)} fichiers HTML")
    
    # Générer le code HTML
    html_template = f'''<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Visualiseur Jobs.ch Local - {len(files_data)} fichiers</title>
    <style>
        * {{
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }}

        body {{
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: #f5f5f7;
            height: 100vh;
            display: flex;
            flex-direction: column;
        }}

        .header {{
            background: #1d1d1f;
            color: white;
            padding: 12px 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            z-index: 1000;
        }}

        .header h1 {{
            font-size: 20px;
            font-weight: 600;
            margin-bottom: 8px;
        }}

        .controls {{
            display: flex;
            gap: 15px;
            align-items: center;
            flex-wrap: wrap;
        }}

        .file-selector {{
            position: relative;
        }}

        .file-selector select {{
            background: #2d2d30;
            color: white;
            border: 1px solid #404040;
            border-radius: 6px;
            padding: 8px 40px 8px 12px;
            font-size: 14px;
            min-width: 300px;
            cursor: pointer;
            appearance: none;
        }}

        .file-selector::after {{
            content: '▼';
            position: absolute;
            right: 12px;
            top: 50%;
            transform: translateY(-50%);
            color: #888;
            pointer-events: none;
            font-size: 12px;
        }}

        .file-info {{
            background: rgba(255,255,255,0.1);
            padding: 6px 12px;
            border-radius: 4px;
            font-size: 12px;
            color: #ccc;
        }}

        .buttons {{
            display: flex;
            gap: 10px;
        }}

        .btn {{
            background: #007aff;
            color: white;
            border: none;
            padding: 8px 16px;
            border-radius: 6px;
            cursor: pointer;
            font-size: 13px;
            font-weight: 500;
            transition: background 0.2s;
        }}

        .btn:hover {{
            background: #0056d6;
        }}

        .btn.secondary {{
            background: #48484a;
        }}

        .btn.secondary:hover {{
            background: #636366;
        }}

        .content {{
            flex: 1;
            display: flex;
            overflow: hidden;
        }}

        .sidebar {{
            width: 350px;
            background: white;
            border-right: 1px solid #d1d1d6;
            overflow-y: auto;
            padding: 20px;
        }}

        .sidebar h3 {{
            color: #1d1d1f;
            margin-bottom: 15px;
            font-size: 16px;
        }}

        .file-list {{
            list-style: none;
        }}

        .file-item {{
            padding: 12px;
            border: 1px solid #e5e5e7;
            border-radius: 8px;
            margin-bottom: 8px;
            cursor: pointer;
            transition: all 0.2s;
            background: #fafafa;
        }}

        .file-item:hover {{
            background: #f0f8ff;
            border-color: #007aff;
        }}

        .file-item.active {{
            background: #007aff;
            color: white;
            border-color: #007aff;
        }}

        .file-name {{
            font-weight: 600;
            margin-bottom: 4px;
            font-size: 14px;
        }}

        .file-meta {{
            font-size: 11px;
            opacity: 0.7;
        }}

        .file-type {{
            display: inline-block;
            background: #34c759;
            color: white;
            padding: 2px 6px;
            border-radius: 3px;
            font-size: 10px;
            font-weight: 500;
            text-transform: uppercase;
            margin-right: 8px;
        }}

        .file-type.stage {{ background: #ff9500; }}
        .file-type.freelance {{ background: #af52de; }}
        .file-type.emploi {{ background: #34c759; }}

        .viewer {{
            flex: 1;
            position: relative;
        }}

        .iframe-container {{
            width: 100%;
            height: 100%;
            position: relative;
        }}

        .viewer-iframe {{
            width: 100%;
            height: 100%;
            border: none;
            background: white;
        }}

        .no-selection {{
            display: flex;
            align-items: center;
            justify-content: center;
            height: 100%;
            color: #86868b;
            font-size: 16px;
            flex-direction: column;
            gap: 10px;
        }}

        .no-selection svg {{
            width: 64px;
            height: 64px;
            opacity: 0.3;
        }}

        .loading {{
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            color: #86868b;
            display: none;
        }}

        .stats {{
            background: rgba(0,122,255,0.1);
            border: 1px solid rgba(0,122,255,0.2);
            border-radius: 6px;
            padding: 8px 12px;
            font-size: 12px;
            color: #007aff;
        }}

        @media (max-width: 768px) {{
            .controls {{
                flex-direction: column;
                align-items: stretch;
            }}
            
            .content {{
                flex-direction: column;
            }}
            
            .sidebar {{
                width: 100%;
                height: 250px;
            }}
        }}
    </style>
</head>
<body>
    <div class="header">
        <h1>📋 Visualiseur Jobs.ch Local</h1>
        <div class="controls">
            <div class="file-selector">
                <select id="fileSelect">
                    <option value="">Sélectionner un fichier... ({len(files_data)} disponibles)</option>
{generate_select_options(files_data)}
                </select>
            </div>
            <div class="file-info" id="fileInfo">
                Aucun fichier sélectionné
            </div>
            <div class="stats">
                {len(files_data)} pages • {sum(f['size'] for f in files_data)/1024/1024:.1f} MB
            </div>
            <div class="buttons">
                <button class="btn" onclick="refreshPage()">🔄 Actualiser</button>
                <button class="btn secondary" onclick="openInNewTab()">🔗 Nouvel onglet</button>
            </div>
        </div>
    </div>

    <div class="content">
        <div class="sidebar">
            <h3>📁 Fichiers disponibles ({len(files_data)})</h3>
            <ul class="file-list" id="fileList">
{generate_file_list_html(files_data)}
            </ul>
        </div>

        <div class="viewer">
            <div class="no-selection" id="noSelection">
                <svg viewBox="0 0 24 24" fill="currentColor">
                    <path d="M14,2H6A2,2 0 0,0 4,4V20A2,2 0 0,0 6,22H18A2,2 0 0,0 20,20V8L14,2M18,20H6V4H13V9H18V20Z" />
                </svg>
                <div>Sélectionnez un fichier pour le visualiser</div>
                <div style="font-size: 12px; opacity: 0.7;">Utilisez ↑↓ pour naviguer</div>
            </div>
            <div class="iframe-container" id="iframeContainer" style="display: none;">
                <div class="loading" id="loading">⏳ Chargement...</div>
                <iframe class="viewer-iframe" id="viewerIframe"></iframe>
            </div>
        </div>
    </div>

    <script>
        const filesData = {json.dumps(files_data, ensure_ascii=False, indent=8)};
        
        let currentFile = '';

        function selectFile(filename) {{
            currentFile = filename;
            
            // Mettre à jour l'interface
            updateActiveFileInList(filename);
            updateFileInfo(filename);
            loadFileInViewer(filename);
            
            // Mettre à jour le sélecteur
            document.getElementById('fileSelect').value = filename;
        }}

        function updateActiveFileInList(filename) {{
            document.querySelectorAll('.file-item').forEach(item => {{
                item.classList.remove('active');
                if (item.dataset.file === filename) {{
                    item.classList.add('active');
                    item.scrollIntoView({{ behavior: 'smooth', block: 'center' }});
                }}
            }});
        }}

        function updateFileInfo(filename) {{
            const fileInfo = document.getElementById('fileInfo');
            const file = filesData.find(f => f.name === filename);
            
            if (file) {{
                const sizeKB = (file.size / 1024).toFixed(1);
                fileInfo.textContent = `${{file.type}} • ${{file.id}} • ${{sizeKB}} KB`;
            }} else {{
                fileInfo.textContent = 'Fichier non trouvé';
            }}
        }}

        function loadFileInViewer(filename) {{
            const noSelection = document.getElementById('noSelection');
            const iframeContainer = document.getElementById('iframeContainer');
            const iframe = document.getElementById('viewerIframe');
            const loading = document.getElementById('loading');

            loading.style.display = 'block';
            noSelection.style.display = 'none';
            iframeContainer.style.display = 'block';

            iframe.src = `{html_dir}/${{filename}}`;
            
            iframe.onload = function() {{
                loading.style.display = 'none';
            }};

            iframe.onerror = function() {{
                loading.style.display = 'none';
                iframe.src = 'data:text/html,<div style="padding: 40px; text-align: center; color: #d1051d; font-family: system-ui;"><h2>❌ Erreur de chargement</h2><p>Impossible de charger le fichier:</p><code>' + filename + '</code><br><br><small>Vérifiez que le fichier existe dans le répertoire {html_dir}/</small></div>';
            }};
        }}

        function refreshPage() {{
            window.location.reload();
        }}

        function openInNewTab() {{
            if (currentFile) {{
                window.open(`{html_dir}/${{currentFile}}`, '_blank');
            }}
        }}

        // Navigation clavier
        document.addEventListener('keydown', function(e) {{
            if (filesData.length === 0) return;
            
            const currentIndex = filesData.findIndex(f => f.name === currentFile);
            
            if (e.key === 'ArrowUp' && currentIndex > 0) {{
                e.preventDefault();
                selectFile(filesData[currentIndex - 1].name);
            }} else if (e.key === 'ArrowDown' && currentIndex < filesData.length - 1) {{
                e.preventDefault();
                selectFile(filesData[currentIndex + 1].name);
            }} else if (e.key === 'Enter' && currentFile) {{
                openInNewTab();
            }}
        }});

        // Event listeners
        document.getElementById('fileSelect').addEventListener('change', function(e) {{
            if (e.target.value) {{
                selectFile(e.target.value);
            }}
        }});

        // Auto-sélectionner le premier fichier si disponible
        if (filesData.length > 0) {{
            setTimeout(() => selectFile(filesData[0].name), 500);
        }}
    </script>
</body>
</html>'''

    # Écrire le fichier HTML
    with open(output_file, 'w', encoding='utf-8') as f:
        f.write(html_template)
    
    print(f"✅ Visualiseur généré: {output_file}")
    print(f"🌐 Ouvrez ce fichier dans Mozilla Firefox pour visualiser vos pages")
    
    return True

def generate_select_options(files_data):
    """Génère les options du sélecteur"""
    options = []
    for file_data in files_data:
        label = f"{file_data['type'].upper()} - {file_data['id']}"
        options.append(f'                    <option value="{file_data["name"]}">{label}</option>')
    return '\n'.join(options)

def generate_file_list_html(files_data):
    """Génère la liste HTML des fichiers"""
    if not files_data:
        return '                <li style="color: #86868b; text-align: center; padding: 20px;">Aucun fichier trouvé dans le répertoire html_pages/</li>'
    
    items = []
    for file_data in files_data:
        size_kb = file_data['size'] / 1024
        items.append(f'''                <li class="file-item" data-file="{file_data['name']}" onclick="selectFile('{file_data['name']}')">
                    <div class="file-name">
                        <span class="file-type {file_data['type']}">{file_data['type']}</span>
                        {file_data['id']}
                    </div>
                    <div class="file-meta">{size_kb:.1f} KB • {file_data.get('date', 'Date inconnue')}</div>
                </li>''')
    
    return '\n'.join(items)

def main():
    """Fonction principale"""
    print("🔧 Génération du visualiseur Jobs.ch...")
    
    # Vérifier si le répertoire html_pages existe
    if not os.path.exists("html_pages"):
        print("❌ Répertoire 'html_pages' non trouvé")
        print("💡 Assurez-vous d'avoir d'abord téléchargé les pages avec le script de téléchargement")
        return
    
    # Générer le visualiseur
    success = generate_viewer_html()
    
    if success:
        print("\n📋 Instructions:")
        print("1. Ouvrez le fichier 'jobs_viewer.html' dans Mozilla Firefox")
        print("2. Utilisez la liste ou le sélecteur pour naviguer entre les pages")
        print("3. Utilisez les flèches ↑↓ du clavier pour naviguer rapidement")
        print("4. Cliquez sur '🔗 Nouvel onglet' pour ouvrir une page dans un nouvel onglet")
        print("\n🔄 Pour mettre à jour après avoir téléchargé de nouvelles pages:")
        print("   Relancez ce script avec: python generate_viewer.py")

if __name__ == "__main__":
    main()
