#!/usr/bin/env python3
import os
import sys
import json
from pathlib import Path
from datetime import datetime
from jinja2 import Template
import base64
import mimetypes

# Template HTML está em arquivo separado

class GalleryGenerator:
    def __init__(self, base_dir):
        self.base_dir = Path(base_dir)
        self.data = {
            'campaign_name': 'Milla Borges - Redação Blindada',
            'organized_date': datetime.now().strftime('%d/%m/%Y às %H:%M'),
            'videos': [],
            'images': [],
            'texts': [],
            'pdfs': [],
            'all_items': []
        }
    
    def get_file_size(self, file_path):
        """Obter tamanho do arquivo formatado"""
        size = file_path.stat().st_size
        if size > 1024 * 1024:
            return f"{size / (1024 * 1024):.1f}"
        else:
            return f"{size / 1024:.1f}"
    
    def read_transcription(self, file_name, prefix):
        """Ler transcrição se existir"""
        texts_dir = self.base_dir / 'textos'
        transc_file = texts_dir / f"{prefix}_{Path(file_name).stem}.txt"
        
        if transc_file.exists():
            try:
                with open(transc_file, 'r', encoding='utf-8') as f:
                    content = f.read()
                    # Extrair apenas o texto corrigido
                    if "=== TRANSCRIÇÃO ORIGINAL" in content:
                        content = content.split("=== TRANSCRIÇÃO ORIGINAL")[0]
                    return content.strip()
            except Exception as e:
                print(f"Erro ao ler transcrição {transc_file}: {e}")
        return None
    
    def get_markdown_download_link(self):
        """Verificar se existe arquivo markdown compilado"""
        copy_bank_path = self.base_dir / 'copy_bank_completo.md'
        if copy_bank_path.exists():
            return 'copy_bank_completo.md'
        return None
    
    def collect_files(self):
        """Coletar todos os arquivos organizados"""
        # Vídeos
        videos_dir = self.base_dir / 'videos'
        if videos_dir.exists():
            for video in videos_dir.glob('*'):
                if video.is_file():
                    item = {
                        'name': video.name,
                        'path': f"videos/{video.name}",
                        'size_mb': self.get_file_size(video),
                        'type': 'video',
                        'mime_type': mimetypes.guess_type(str(video))[0] or 'video/mp4',
                        'transcription': self.read_transcription(video.name, 'transc_video')
                    }
                    self.data['videos'].append(item)
                    self.data['all_items'].append(item)
        
        # Imagens
        images_dir = self.base_dir / 'imagens'
        if images_dir.exists():
            for image in images_dir.glob('*'):
                if image.is_file():
                    item = {
                        'name': image.name,
                        'path': f"imagens/{image.name}",
                        'size_mb': self.get_file_size(image),
                        'type': 'image',
                        'text': self.read_transcription(image.name, 'transc_imagem')
                    }
                    self.data['images'].append(item)
                    self.data['all_items'].append(item)
        
        # PDFs
        pdfs_dir = self.base_dir / 'pdfs'
        if pdfs_dir.exists():
            for pdf in pdfs_dir.glob('*.pdf'):
                item = {
                    'name': pdf.name,
                    'path': f"pdfs/{pdf.name}",
                    'size_mb': self.get_file_size(pdf),
                    'type': 'pdf',
                    'text': self.read_transcription(pdf.name, 'transc_pdf')
                }
                self.data['pdfs'].append(item)
                self.data['all_items'].append(item)
        
        # Textos
        texts_dir = self.base_dir / 'textos'
        if texts_dir.exists():
            for text in texts_dir.glob('*.txt'):
                if not text.name.startswith('transc_'):
                    try:
                        with open(text, 'r', encoding='utf-8') as f:
                            content = f.read()
                        item = {
                            'name': text.name,
                            'path': f"textos/{text.name}",
                            'size_kb': self.get_file_size(text),
                            'type': 'text',
                            'content': content
                        }
                        self.data['texts'].append(item)
                        self.data['all_items'].append(item)
                    except Exception as e:
                        print(f"Erro ao ler texto {text}: {e}")
        
        # Estatísticas
        self.data['stats'] = {
            'total': len(self.data['all_items']),
            'videos': len(self.data['videos']),
            'images': len(self.data['images']),
            'texts': len(self.data['texts']),
            'pdfs': len(self.data['pdfs'])
        }
    
    def generate_gallery(self):
        """Gerar arquivo HTML da galeria"""
        # Adicionar link do markdown se existir
        self.data['markdown_link'] = self.get_markdown_download_link()
        
        # Ler template do arquivo
        template_path = Path(__file__).parent / 'gallery_template.html'
        with open(template_path, 'r', encoding='utf-8') as f:
            template_html = f.read()
        
        template = Template(template_html)
        html_content = template.render(**self.data)
        
        output_path = self.base_dir / 'galeria_campanha.html'
        with open(output_path, 'w', encoding='utf-8') as f:
            f.write(html_content)
        
        print(f"Galeria gerada em: {output_path}")
        return output_path

def main():
    if len(sys.argv) != 2:
        print("Uso: python generate_gallery.py <diretório>")
        sys.exit(1)
    
    base_dir = sys.argv[1]
    
    if not os.path.exists(base_dir):
        print(f"Erro: Diretório '{base_dir}' não encontrado.")
        sys.exit(1)
    
    generator = GalleryGenerator(base_dir)
    generator.collect_files()
    gallery_path = generator.generate_gallery()
    
    print(f"\nGaleria HTML criada com sucesso!")
    print(f"Abra o arquivo para visualizar: {gallery_path}")

if __name__ == "__main__":
    main()