"""Parser for Pod101 vocabulary exports.

This module handles vocabulary CSV files exported from Pod101 language learning
sites (FinnishPod101, SpanishPod101, etc.).
"""

import csv
from pathlib import Path
from typing import List

from ..models import Entry
from ..utils.encoding import detect_encoding
from ..utils.normalization import normalize_translation


class Pod101Parser:
    """Parser for Pod101 vocabulary exports (CSV format).

    Pod101 sites allow Premium subscribers to export their Word Bank as a CSV file.
    The format is simple:
    - Two-column CSV with header "Word,English"
    - Often UTF-16 encoded with BOM (auto-detected)
    - No example sentences included
    - Translations may use slash, semicolon, or comma separators

    Example CSV:
        Word,English
        ainakin,at least
        joko...tai,either... or
        kahvi,coffee
    """

    @property
    def name(self) -> str:
        """Return the parser name."""
        return "pod101"

    @property
    def description(self) -> str:
        """Return a description of the format."""
        return "Pod101 vocabulary export (UTF-16 CSV with Word,English columns)"

    def parse(self, file_path: Path) -> List[Entry]:
        """Parse Pod101 CSV file.

        Args:
            file_path: Path to the Pod101 CSV export file

        Returns:
            List of Entry objects with word and translation (no example sentences)

        Raises:
            FileNotFoundError: If the file doesn't exist
            ValueError: If the CSV is malformed or missing required columns

        Example:
            >>> parser = Pod101Parser()
            >>> entries = parser.parse(Path("finnishpod101_export.csv"))
            >>> entries[0].word
            'ainakin'
            >>> entries[0].translation
            'at least'
            >>> entries[0].example
            ''
        """
        if not file_path.exists():
            raise FileNotFoundError(f"File not found: {file_path}")

        # Detect encoding (Pod101 often uses UTF-16 with BOM)
        encoding = detect_encoding(file_path)

        entries = []

        try:
            with open(file_path, newline="", encoding=encoding) as f:
                reader = csv.DictReader(f)

                # Validate that required columns exist
                if reader.fieldnames and (
                    "Word" not in reader.fieldnames
                    or "English" not in reader.fieldnames
                ):
                    raise ValueError(
                        "CSV must have 'Word' and 'English' columns. "
                        f"Found columns: {reader.fieldnames}"
                    )

                for row in reader:
                    word = row.get("Word", "").strip()
                    translation = row.get("English", "").strip()

                    # Skip empty rows
                    if word:
                        entries.append(
                            Entry(
                                word=word,
                                translation=normalize_translation(translation),
                                example="",  # Pod101 exports don't include examples
                            )
                        )

        except UnicodeDecodeError as e:
            raise ValueError(
                f"Failed to decode file with {encoding} encoding. "
                f"The file may be corrupted or in an unexpected format: {e}"
            ) from e

        return entries
