"""
🎯 Book Generator
================
Convert directories of markdown files into professional books
"""

import os
import logging
from pathlib import Path
from typing import Dict, List, Optional, Any
from datetime import datetime

from .generator import PDFGenerator

class BookGenerator:
    """
    Generate professional books from markdown file directories
    """
    
    def __init__(self, pdf_generator: Optional[PDFGenerator] = None):
        """
        Initialize book generator
        
        Args:
            pdf_generator: PDF generator instance (optional)
        """
        self.pdf_generator = pdf_generator or PDFGenerator()
        self.logger = logging.getLogger(__name__)
    
    def generate_book(self,
                      input_dir: Path,
                      output_file: Path,
                      template: str = "technical",
                      title: Optional[str] = None,
                      author: Optional[str] = None,
                      recursive: bool = True,
                      file_pattern: str = "*.md",
                      **kwargs) -> Dict[str, Any]:
        """
        Generate book from markdown files
        
        Args:
            input_dir: Directory containing markdown files
            output_file: Output PDF file path
            template: Template name
            title: Book title (auto-generated if None)
            author: Book author
            recursive: Search subdirectories
            file_pattern: File pattern to match
            **kwargs: Additional template parameters
            
        Returns:
            Generation result
        """
        try:
            input_path = Path(input_dir)
            if not input_path.exists():
                raise FileNotFoundError(f"Input directory not found: {input_path}")
            
            # Find markdown files
            markdown_files = self._find_markdown_files(input_path, recursive, file_pattern)
            
            if not markdown_files:
                raise ValueError(f"No markdown files found in {input_path}")
            
            self.logger.info(f"Found {len(markdown_files)} markdown files")
            
            # Combine files into single content
            combined_content = self._combine_files(markdown_files)
            
            # Generate metadata
            book_title = title or self._generate_title(input_path)
            book_author = author or "Generated by WOT-PDF"
            
            # Generate PDF
            result = self.pdf_generator.generate(
                input_content=combined_content,
                output_file=output_file,
                template=template,
                title=book_title,
                author=book_author,
                **kwargs
            )
            
            # Add book-specific metadata
            if result.get("success"):
                result.update({
                    "book_title": book_title,
                    "book_author": book_author,
                    "source_files": len(markdown_files),
                    "source_directory": str(input_path)
                })
            
            return result
            
        except Exception as e:
            self.logger.error(f"Book generation failed: {e}")
            return {
                "success": False,
                "error": str(e),
                "source_directory": str(input_dir)
            }
    
    def _find_markdown_files(self, 
                           directory: Path, 
                           recursive: bool, 
                           pattern: str) -> List[Path]:
        """Find markdown files in directory"""
        files = []
        
        if recursive:
            # Recursive search
            for file_path in directory.rglob(pattern):
                if file_path.is_file():
                    files.append(file_path)
        else:
            # Non-recursive search
            for file_path in directory.glob(pattern):
                if file_path.is_file():
                    files.append(file_path)
        
        # Sort files for consistent ordering
        return sorted(files)
    
    def _combine_files(self, files: List[Path]) -> str:
        """Combine multiple markdown files into single content"""
        combined_lines = []
        
        for file_path in files:
            try:
                # Add file separator comment
                # Don't add HTML comments for Typst compatibility
                # combined_lines.append(f"<!-- Source: {file_path.name} -->")
                combined_lines.append("")
                
                # Read file content
                with open(file_path, 'r', encoding='utf-8') as f:
                    content = f.read().strip()
                    combined_lines.append(content)
                
                combined_lines.append("")
                combined_lines.append("---")  # Section separator
                combined_lines.append("")
                
            except Exception as e:
                self.logger.warning(f"Failed to read {file_path}: {e}")
                combined_lines.append(f"<!-- Error reading {file_path.name}: {e} -->")
                combined_lines.append("")
        
        return "\n".join(combined_lines)
    
    def _generate_title(self, input_dir: Path) -> str:
        """Generate book title from directory name"""
        dir_name = input_dir.name
        
        # Clean up directory name
        title = dir_name.replace('_', ' ').replace('-', ' ')
        title = ' '.join(word.capitalize() for word in title.split())
        
        # Add "Guide" or "Manual" suffix if not present
        if not any(suffix in title.lower() for suffix in ['guide', 'manual', 'book', 'documentation']):
            title += " Guide"
        
        return title
