"""Parser for Language Reactor vocabulary exports.

This module handles vocabulary TSV files exported from the Language Reactor
browser extension for language learning through Netflix and YouTube.
"""

import csv
import io
from pathlib import Path
from typing import List

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


class LanguageReactorParser:
    """Parser for Language Reactor vocabulary exports (TSV format).

    Language Reactor allows Pro subscribers to export saved words from their
    Saved Items panel. The format is tab-separated with complex structure:

    Columns (0-indexed):
    - 0: WORD|<base_form>|<lang>
    - 1: type (Word / Phrase)
    - 2: example sentence (target language)
    - 3: example sentence translation (English)
    - 4: inflected form found in context
    - 5: base / dictionary form
    - 6: POS tag
    - 7: (empty)
    - 8: translation(s), e.g., "put, to put, to place"
    - 9+: source, language codes, timestamps, full sentence blocks

    The parser extracts the base form (column 5), translation (column 8),
    and example sentence (column 2).
    """

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

    @property
    def description(self) -> str:
        """Return a description of the format."""
        return (
            "Language Reactor saved words export "
            "(TSV with base forms and example sentences)"
        )

    def parse(self, file_path: Path) -> List[Entry]:
        """Parse Language Reactor TSV file.

        Args:
            file_path: Path to the Language Reactor TSV export file

        Returns:
            List of Entry objects with word, translation, and example sentence.
            The example sentence is extracted from the subtitle context where
            the word was found, and may contain an inflected form rather than
            the dictionary form.

        Raises:
            FileNotFoundError: If the file doesn't exist
            UnicodeDecodeError: If the file cannot be decoded as UTF-8

        Example:
            >>> parser = LanguageReactorParser()
            >>> entries = parser.parse(Path("saved_items.csv"))
            >>> entries[0].word  # Base/dictionary form
            'käydä'
            >>> entries[0].translation
            'to visit / to go'
            >>> entries[0].example  # Sentence from subtitle
            'Kävin kaupassa eilen'
        """
        if not file_path.exists():
            raise FileNotFoundError(f"File not found: {file_path}")

        entries = []

        with open(file_path, encoding="utf-8") as f:
            content = f.read()

        # Parse as tab-separated, handling quoted fields
        reader = csv.reader(
            io.StringIO(content), delimiter="\t", quotechar='"'
        )

        for cols in reader:
            # Skip rows that don't start with WORD| marker
            if not cols or not cols[0].startswith("WORD|"):
                continue

            # Extract base form (column 5, fallback to parsing column 0)
            base_form = cols[5].strip() if len(cols) > 5 else ""
            if not base_form:
                # Fallback: parse "WORD|<base>|<lang>" from column 0
                parts = cols[0].split("|")
                base_form = parts[1] if len(parts) > 1 else cols[0]

            # Extract translation (column 8)
            translation = ""
            if len(cols) > 8:
                translation = cols[8].strip().strip('"')

            # Extract example sentence (column 2)
            example = ""
            if len(cols) > 2:
                example = cols[2].strip().strip('"')

            # Skip entries without a base form
            if base_form:
                entries.append(
                    Entry(
                        word=base_form,
                        translation=normalize_translation(translation),
                        example=example,
                    )
                )

        return entries
