import random
from typing import Optional

from sqlalchemy.orm import Session

from models import DictionaryEntry


class DictionaryService:
    def lookup_en(self, db: Session, text: str) -> Optional[DictionaryEntry]:
        key = text.lower().strip()
        if not key:
            return None
        return db.query(DictionaryEntry).filter(DictionaryEntry.lemma_en == key).first()

    def lookup_zh(self, db: Session, text: str) -> Optional[DictionaryEntry]:
        text = text.strip()
        if not text:
            return None
        entry = db.query(DictionaryEntry).filter(DictionaryEntry.zh == text).first()
        if entry:
            return entry
        return (
            db.query(DictionaryEntry)
            .filter(DictionaryEntry.zh.contains(text))
            .first()
        )

    def random_zh_values(self, db: Session, exclude: str, limit: int) -> list[str]:
        rows = (
            db.query(DictionaryEntry.zh)
            .filter(DictionaryEntry.zh != exclude)
            .order_by(DictionaryEntry.id)
            .all()
        )
        values = [r[0] for r in rows]
        random.shuffle(values)
        return values[:limit]

    def random_en_lemmas(self, db: Session, exclude: str, limit: int) -> list[str]:
        rows = (
            db.query(DictionaryEntry.lemma_en)
            .filter(DictionaryEntry.lemma_en != exclude.lower())
            .order_by(DictionaryEntry.id)
            .all()
        )
        values = [r[0] for r in rows]
        random.shuffle(values)
        return values[:limit]

    def count(self, db: Session) -> int:
        return db.query(DictionaryEntry).count()


dictionary_service = DictionaryService()
