"""Core conversion API for words-to-readlang.

This module provides the high-level Converter class that orchestrates
the entire conversion pipeline from input format to Readlang CSV.
"""

from pathlib import Path
from typing import List, Optional

from .models import Entry
from .parsers import get_parser
from .services.fetcher import ExampleFetcher
from .writers.readlang import ReadlangWriter


class Converter:
    """High-level API for converting vocabulary files to Readlang format.

    This class provides a simple interface for the complete conversion pipeline:
    1. Parse input file using the specified parser
    2. Optionally fetch example sentences from Tatoeba or Leipzig
    3. Write to Readlang CSV format (with automatic file splitting)

    Example:
        >>> from pathlib import Path
        >>> converter = Converter(fetch_examples=True, src_lang="fin")
        >>> output_files = converter.convert(
        ...     input_path=Path("words.csv"),
        ...     output_path=Path("readlang.csv"),
        ...     parser_name="pod101"
        ... )
        >>> print(f"Created {len(output_files)} file(s)")
        Created 1 file(s)
    """

    def __init__(
        self,
        fetch_examples: bool = False,
        src_lang: str = "fin",
        fetch_delay: float = 0.5,
        prefer: str = "tatoeba",
        verbose: bool = True,
    ):
        """Initialize the converter with configuration options.

        Args:
            fetch_examples: Whether to fetch missing example sentences from an
                           external source. If False, entries with invalid
                           examples will have empty example fields. (default: False)
            src_lang: Source language code for example lookups (e.g., 'fin', 'swe').
                     Only used if fetch_examples=True. (default: "fin")
            fetch_delay: Seconds to wait between Tatoeba API requests to avoid
                        overwhelming their servers. (default: 0.5)
            prefer: Which source to try first when fetching examples —
                    ``"tatoeba"`` (default) or ``"leipzig"``. The other is
                    used as fallback. Only used if fetch_examples=True.
            verbose: Whether to print progress messages to stderr. (default: True)
        """
        self.fetch_examples = fetch_examples
        self.src_lang = src_lang
        self.prefer = prefer
        self.verbose = verbose

        # Initialize example fetcher if needed
        self.example_fetcher: Optional[ExampleFetcher] = None
        if fetch_examples:
            self.example_fetcher = ExampleFetcher(
                delay=fetch_delay, verbose=verbose
            )

    def convert(
        self,
        input_path: Path,
        output_path: Path,
        parser_name: str,
    ) -> List[Path]:
        """Convert vocabulary file to Readlang format.

        This is the main entry point for the conversion process.

        Args:
            input_path: Path to input vocabulary file
            output_path: Path for output file (may create multiple if >200 entries)
            parser_name: Name of parser to use ('pod101', 'languagereactor', etc.)

        Returns:
            List of paths to created output files (may be multiple due to
            Readlang's 200-entry limit)

        Raises:
            FileNotFoundError: If input_path doesn't exist
            ValueError: If parser_name is not recognized, or if no entries found
            IOError: If output file cannot be written

        Example:
            >>> converter = Converter()
            >>> paths = converter.convert(
            ...     input_path=Path("export.csv"),
            ...     output_path=Path("readlang.csv"),
            ...     parser_name="pod101"
            ... )
            Wrote 42 entries to readlang.csv
            >>> paths
            [PosixPath('readlang.csv')]
        """
        # Validate input file exists
        if not input_path.exists():
            raise FileNotFoundError(f"Input file not found: {input_path}")

        # Get parser and parse input
        parser = get_parser(parser_name)
        entries = parser.parse(input_path)

        if not entries:
            raise ValueError(
                f"No entries found in {input_path}. "
                "Check that the file matches the expected format."
            )

        # Write to Readlang format
        writer = ReadlangWriter(
            example_fetcher=self.example_fetcher, src_lang=self.src_lang
        )

        output_paths = writer.write(
            entries, output_path, fetch_examples=self.fetch_examples,
            prefer=self.prefer,
        )

        return output_paths
