import re
from typing import Optional

from sqlalchemy.orm import Session

from services.dictionary_service import dictionary_service


def contains_chinese(text: str) -> bool:
    return bool(re.search(r"[\u4e00-\u9fff]", text))


class TranslationService:
    """翻译服务：优先查离线词典表，未命中时返回占位结果（暂不接入外部 API）。"""

    def translate(self, db: Session, text: str) -> dict:
        text = text.strip()
        if not text:
            raise ValueError("输入不能为空")

        if contains_chinese(text):
            return self._zh_to_en(db, text)
        return self._en_to_zh(db, text)

    def _en_to_zh(self, db: Session, text: str) -> dict:
        entry = dictionary_service.lookup_en(db, text)
        if entry:
            return self._build_response(
                text,
                entry.zh,
                "en",
                "zh",
                entry.phonetic,
                entry.example_en,
                entry.example_cn,
            )
        return self._placeholder(text, "en", "zh")

    def _zh_to_en(self, db: Session, text: str) -> dict:
        entry = dictionary_service.lookup_zh(db, text)
        if entry:
            return self._build_response(
                text,
                entry.lemma_en,
                "zh",
                "en",
                entry.phonetic,
                entry.example_en,
                entry.example_cn,
            )
        return self._placeholder(text, "zh", "en")

    def _build_response(
        self,
        source: str,
        target: str,
        source_lang: str,
        target_lang: str,
        phonetic: Optional[str],
        example_en: Optional[str],
        example_cn: Optional[str],
    ) -> dict:
        return {
            "source_text": source,
            "target_text": target,
            "source_lang": source_lang,
            "target_lang": target_lang,
            "phonetic": phonetic,
            "example_en": example_en,
            "example_cn": example_cn,
            "found": True,
        }

    def _placeholder(self, source: str, source_lang: str, target_lang: str) -> dict:
        return {
            "source_text": source,
            "target_text": "",
            "source_lang": source_lang,
            "target_lang": target_lang,
            "phonetic": None,
            "example_en": None,
            "example_cn": None,
            "found": False,
        }


translation_service = TranslationService()
