import json
import os
from typing import List, Dict, Any, Optional
from ..base import BaseRule, Diagnostic

try:
    from openai import OpenAI
except ImportError:
    OpenAI = None


class LLMTypoRule(BaseRule):
    rule_id = "llm-chinese-typo"
    severity = "warning"
    DEFAULT_MODEL = "gpt-3.5-turbo"

    def __init__(self, config: Optional[Dict[str, Any]] = None):
        super().__init__(config)
        self.model = self.config.get("model", self.DEFAULT_MODEL)
        self.api_key = self.config.get("api_key", os.getenv("DOC_LINT_LLM_KEY"))
        self.base_url = self.config.get("base_url", "https://api.openai.com/v1")
        self.timeout = self.config.get("timeout", 30)
        self.max_tokens = self.config.get("max_tokens", 1024)
        self.res_json = {"errors": [{"line": "行号", "error": "错词", "suggestion": "建议"}]}

    def _get_model_config(self, config: Optional[Dict[str, Any]]) -> str:
        """
        获取模型配置，支持规则级和全局级配置
        优先级：规则配置 > 全局 LLM 配置 > 默认值
        """
        if config and "model" in config:
            return config["model"]
        # 可从这里扩展读取全局配置
        return self.DEFAULT_MODEL

    def check(self, file_path: str, content: str) -> List[Diagnostic]:
        diagnostics = []

        if not self.api_key:
            print(f"[WARN] LLM Key not found, skipping rule {self.rule_id} for {file_path}")
            return []

        try:
            print(f"[INFO] Running {self.rule_id} with model: {self.model}")

            # --- 实际 LLM 调用逻辑示例 ---
            client = OpenAI(api_key=self.api_key, base_url=self.base_url)
            response = client.chat.completions.create(
                model=self.model,
                messages=[{"role": "user", "content": f"检查以下文本的中文错别字：{content}，返回 JSON 格式：{self.res_json}"}],
                max_tokens=self.max_tokens,
                timeout=self.timeout
            )
            # 解析 response 并生成 diagnostics
            result_content = response.choices[0].message.content
            if result_content:
                result = json.loads(result_content)
                for err in result.get("errors", []):
                    diagnostics.append(Diagnostic(file_path, err.get("line", 1), 1,
                                                  f"疑似错别字：\"{err.get('error')}\"",
                                                  self.severity, self.rule_id))
        except Exception as e:
            print(f"[ERROR] LLM check failed: {e}")

        return diagnostics
