"""Entry validation service."""

from typing import Tuple

from ..database import db
from ..models import Entry


class ValidationService:
    """Service for validating vocabulary entries."""

    @staticmethod
    def validate_entry(entry: Entry) -> str:
        """Validate an entry and return validation status.

        Checks if the example sentence contains the word.
        Uses case-insensitive matching.

        Args:
            entry: Entry object to validate

        Returns:
            Validation status: "valid", "invalid_no_example", or "invalid_word_missing"
        """
        word = entry.current_word
        example = entry.current_example

        # Extract first synonym (word before ' / ')
        first_word = word.split(" / ")[0].strip()

        # Check if example exists
        if not example or not example.strip():
            return "invalid_no_example"

        # Check if word appears in example (case-insensitive)
        if first_word.lower() in example.lower():
            return "valid"
        else:
            return "invalid_word_missing"

    @staticmethod
    def update_entry_validation(entry: Entry) -> str:
        """Update an entry's validation status.

        Args:
            entry: Entry object to validate and update

        Returns:
            New validation status
        """
        status = ValidationService.validate_entry(entry)
        entry.validation_status = status
        db.session.commit()
        return status

    @staticmethod
    def validate_upload(upload_id: int) -> Tuple[int, int, int]:
        """Validate all entries in an upload.

        Args:
            upload_id: Upload ID to validate

        Returns:
            Tuple of (valid_count, invalid_no_example_count, invalid_word_missing_count)
        """
        entries = Entry.query.filter_by(upload_id=upload_id).all()

        valid_count = 0
        no_example_count = 0
        word_missing_count = 0

        for entry in entries:
            status = ValidationService.validate_entry(entry)
            entry.validation_status = status

            if status == "valid":
                valid_count += 1
            elif status == "invalid_no_example":
                no_example_count += 1
            elif status == "invalid_word_missing":
                word_missing_count += 1

        db.session.commit()

        return (valid_count, no_example_count, word_missing_count)
