"""Export service for CSV and ZIP generation."""

import tempfile
import zipfile
from pathlib import Path
from typing import Tuple

from words_to_readlang.models import Entry as LibEntry
from words_to_readlang.writers.readlang import ReadlangWriter

from ..models import Entry


class ExportService:
    """Service for exporting entries to Readlang format."""

    @staticmethod
    def export_upload(upload_id: int, fetch_examples: bool = False) -> Tuple[Path, str, str, int, int]:
        """Export upload to CSV or ZIP file.

        Args:
            upload_id: Upload ID to export
            fetch_examples: Whether to fetch examples from Tatoeba (not implemented yet)

        Returns:
            Tuple of (file_path, mime_type, filename, valid_count, excluded_count)
            - If ≤200 entries: (csv_path, 'text/csv', 'readlang.csv', count, excluded)
            - If >200 entries: (zip_path, 'application/zip', 'readlang.zip', count, excluded)

        Raises:
            ValueError: If upload has no valid entries to export
        """
        # Fetch ALL entries from database
        all_entries = Entry.query.filter_by(upload_id=upload_id).all()

        if not all_entries:
            raise ValueError("No entries found for this upload")

        # Filter to ONLY valid entries
        valid_entries = [e for e in all_entries if e.validation_status == "valid"]

        if not valid_entries:
            raise ValueError("No valid entries to export. Please fix validation errors first.")

        excluded_count = len(all_entries) - len(valid_entries)
        entries = valid_entries

        # Convert database entries to library Entry objects
        lib_entries = [
            LibEntry(
                word=e.current_word,
                translation=e.current_translation,
                example=e.current_example,
                score="",
                date="",
            )
            for e in entries
        ]

        # Create temporary directory for output
        temp_dir = Path(tempfile.mkdtemp())
        output_path = temp_dir / "readlang.csv"

        # Use existing ReadlangWriter
        writer = ReadlangWriter()
        paths = writer.write(lib_entries, output_path, fetch_examples=False)

        # If multiple files, create ZIP
        if len(paths) > 1:
            zip_path = temp_dir / "readlang.zip"
            with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as zf:
                for path in paths:
                    zf.write(path, path.name)

            return (zip_path, "application/zip", "readlang.zip", len(valid_entries), excluded_count)
        else:
            return (paths[0], "text/csv", "readlang.csv", len(valid_entries), excluded_count)
