"""Text utilities and prompt building for translation."""

import re


class TextUtils:
    """Utilities for text processing."""

    def __init__(self):
        self.language_names = {
            "en": "English",
            "ru": "Russian",
            "ko": "Korean",
            "zh": "Chinese",
            "ja": "Japanese",
            "es": "Spanish",
            "fr": "French",
            "de": "German",
            "it": "Italian",
            "pt": "Portuguese",
            "ar": "Arabic",
            "hi": "Hindi",
            "tr": "Turkish",
            "pl": "Polish",
            "uk": "Ukrainian",
            "be": "Belarusian",
            "kk": "Kazakh"
        }

    def needs_translation(
        self,
        text: str,
        source_language: str,
        target_language: str,
        script_detector=None
    ) -> bool:
        """
        Determine if text needs translation.

        Args:
            text: Text to check
            source_language: Source language code
            target_language: Target language code
            script_detector: Optional ScriptDetector for CJK check

        Returns:
            True if translation is needed
        """
        if not text or not text.strip():
            return False

        if self.is_technical_content(text):
            return False

        if source_language == target_language:
            return False

        if script_detector and script_detector.contains_cjk(text):
            return True

        if source_language == 'auto':
            if script_detector:
                detected_lang = script_detector.detect_language(text)
                return detected_lang != target_language

        return True

    def is_technical_content(self, text: str) -> bool:
        """
        Check if text is technical content that shouldn't be translated.

        Args:
            text: Text to check

        Returns:
            True if text is technical content
        """
        # URLs
        if text.startswith(('http://', 'https://', '//', 'www.')):
            return True

        # File paths
        if '/' in text and ('.' in text or text.startswith('/')):
            return True

        # Numbers only
        if re.match(r'^\d+(\.\d+)?$', text.strip()):
            return True

        # Technical identifiers
        if re.match(r'^[A-Z_][A-Z0-9_]*$', text):
            return True

        return False

    def get_language_name(self, code: str) -> str:
        """Get full language name from code."""
        return self.language_names.get(code, code)


class PromptBuilder:
    """Build prompts for translation."""

    def __init__(self):
        self.language_names = {
            "en": "English",
            "ru": "Russian",
            "ko": "Korean",
            "zh": "Chinese",
            "ja": "Japanese",
            "es": "Spanish",
            "fr": "French",
            "de": "German",
            "it": "Italian",
            "pt": "Portuguese",
            "ar": "Arabic",
            "hi": "Hindi",
            "tr": "Turkish",
            "pl": "Polish",
            "uk": "Ukrainian",
            "be": "Belarusian",
            "kk": "Kazakh"
        }

    def build_text_translation_prompt(
        self,
        text: str,
        source_language: str,
        target_language: str
    ) -> str:
        """
        Build prompt for text translation.

        Args:
            text: Text to translate
            source_language: Source language code
            target_language: Target language code

        Returns:
            Translation prompt
        """
        source_name = self.language_names.get(source_language, source_language)
        target_name = self.language_names.get(target_language, target_language)

        prompt = f"""You are a professional translator. Translate the following text from {source_name} to {target_name}.

IMPORTANT INSTRUCTIONS:
1. Translate ONLY the text provided
2. Preserve original formatting, numbers, URLs, and technical values
3. Keep the translation accurate and natural
4. Return ONLY the translation, no explanations or comments
5. If the text contains mixed languages, translate only the parts in {source_name}

Text to translate:
{text}

Translation:"""

        return prompt

    def build_json_translation_prompt(
        self,
        json_str: str,
        source_language: str,
        target_language: str
    ) -> str:
        """
        Build prompt for JSON translation.

        Args:
            json_str: JSON string to translate
            source_language: Source language code
            target_language: Target language code

        Returns:
            JSON translation prompt
        """
        prompt = f"""You are a professional translator. Your task is to translate ONLY the VALUES in this JSON, NEVER the keys.

CRITICAL RULES - VIOLATION WILL RESULT IN FAILURE:
1. NEVER TRANSLATE JSON KEYS: "title" stays "title", NOT "titulo" or "заголовок"
2. NEVER TRANSLATE JSON KEYS: "description" stays "description", NOT "descripcion" or "описание"
3. NEVER TRANSLATE JSON KEYS: "navigation" stays "navigation", NOT "navegacion" or "навигация"
4. ONLY translate the VALUES: "Hello" -> "Hola", "World" -> "Mundo"
5. DO NOT translate: URLs, emails, numbers, booleans, null, empty strings, "SKIP_TRANSLATION"
6. Keep exact JSON structure and key names in English

WRONG EXAMPLE (DO NOT DO THIS):
{{"titulo": "Hola", "descripcion": "Mundo"}}

CORRECT EXAMPLE (DO THIS):
{{"title": "Hola", "description": "Mundo"}}

If you translate ANY JSON key, you have FAILED the task completely.

JSON to translate from {source_language} to {target_language}:
{json_str}

Return ONLY the JSON with translated VALUES and original English keys:"""

        return prompt
