import json
import logging
import random
from pathlib import Path

import requests

logger = logging.getLogger(__name__)


class TranslationService:
    DEFAULT_HOST = "https://translate.googleapis.com"
    LANG_MAP = {
        "zh-CN": "简体中文",
        "en": "English",
        "ja": "日本語",
        "ko": "한국어",
    }

    def __init__(self, bridge, mirror_path: Path = None):
        self.bridge = bridge
        self.mirror_path = mirror_path
        self.mirrors = []
        self._load_mirrors()

    def _load_mirrors(self):
        if self.mirror_path and self.mirror_path.exists():
            try:
                with open(self.mirror_path, encoding="utf-8") as f:
                    self.mirrors = json.load(f)
            except Exception as e:
                logger.warning(f"Error loading mirrors from {self.mirror_path}: {e}")

    def get_host(self):
        if self.bridge.translationMode == "mirror" and self.mirrors:
            return random.choice(self.mirrors)
        return self.DEFAULT_HOST

    def is_target_lang(self, text, lang_code):
        has_ja = any("\u3040" <= char <= "\u30ff" for char in text)
        has_ko = any("\uac00" <= char <= "\ud7a3" for char in text)

        if lang_code == "zh-CN":
            has_zh = any("\u4e00" <= char <= "\u9fff" for char in text)
            return has_zh and not has_ja and not has_ko
        if lang_code == "ja":
            return has_ja
        if lang_code == "ko":
            return has_ko
        if lang_code == "en":
            # Simple check for ASCII/English
            return all(
                ord(char) < 128
                for char in text.replace(" ", "").replace("\n", "").replace("\r", "")
            )
        return False

    def translate(self, text, request_id=0):
        default = self.bridge.defaultLang
        if self.is_target_lang(text, default):
            target_lang = "en"
        elif default == "en" and self.is_target_lang(text, "en"):
            target_lang = "zh-CN"
        else:
            target_lang = default

        params = {
            "client": "gtx",
            "sl": "auto",
            "tl": target_lang,
            "dj": "1",
            "q": text,
        }
        for dt in ["t", "bd", "qc", "rm", "ex", "at", "ss", "rw", "ld"]:
            params.setdefault("dt", []).append(dt)

        headers = {
            "Accept": "application/json, text/plain, */*",
            "Accept-Encoding": "gzip",
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
        }

        try:
            host = self.get_host()
            try:
                response = requests.get(
                    f"{host}/translate_a/single",
                    params=params,
                    headers=headers,
                    timeout=5,
                )
                response.raise_for_status()
            except (requests.RequestException, Exception):
                # Fallback to default host
                if host != self.DEFAULT_HOST:
                    response = requests.get(
                        f"{self.DEFAULT_HOST}/translate_a/single",
                        params=params,
                        headers=headers,
                        timeout=5,
                    )
                    response.raise_for_status()
                else:
                    raise

            self._process_data(response.json(), request_id)
        except Exception as e:
            logger.error(f"Translation error for text '{text[:20]}...': {e}")
            self.bridge.translationError.emit(str(e))

    def _process_data(self, data, request_id=0):
        result = {"word": False, "dicts": [], "trans": [], "requestId": request_id}
        if "dict" in data:
            result["word"] = True
            for item in data["dict"]:
                result["dicts"].append(
                    {"pos": item.get("pos", ""), "terms": item.get("terms", [])}
                )
        else:
            sentences = data.get("sentences", [])
            paragraphs = []
            current_para = ""
            for s in sentences:
                t = s.get("trans", "")
                if not t:
                    continue
                current_para += t
                if t.endswith("\n"):
                    paragraphs.append(current_para.strip())
                    current_para = ""
            if current_para.strip():
                paragraphs.append(current_para.strip())
            for p in paragraphs:
                result["trans"].append({"typ": 0, "data": p})

        self.bridge.translationReceived.emit(result)
