import json
import anthropic
from krrkt.providers.base import LLMProvider


FINDINGS_SCHEMA = {
    "type": "object",
    "properties": {
        "findings": {
            "type": "array",
            "items": {
                "type": "object",
                "properties": {
                    "start": {"type": "integer", "description": "Start position in original text"},
                    "end": {"type": "integer", "description": "End position in original text"},
                    "word": {"type": "string", "description": "The problematic word or phrase"},
                    "rule": {"type": "string", "description": "Rule category name"},
                    "section": {"type": "string", "description": "Section for grouping"},
                    "description": {"type": "string", "description": "Brief recommendation"},
                    "weight": {"type": "integer", "description": "Severity 0-100"},
                    "style": {"type": "string", "enum": ["red", "blue", "orange"]},
                    "tab": {"type": "string", "enum": ["red", "blue"]},
                },
                "required": ["start", "end", "word", "rule", "weight", "style", "tab"],
                "additionalProperties": False,
            }
        }
    },
    "required": ["findings"],
    "additionalProperties": False,
}


class AnthropicProvider(LLMProvider):
    def __init__(self, model: str = "claude-sonnet-4-6"):
        self.client = anthropic.Anthropic()
        self.model = model

    async def analyze(self, text: str, system_prompt: str,
                      already_found: list[dict]) -> list[dict]:
        already_desc = ""
        if already_found:
            items = [f"- \"{f.get('word', '')}\" ({f.get('rule', '')})" for f in already_found]
            already_desc = "\n\nУже найденные проблемы (НЕ дублируй их):\n" + "\n".join(items)

        user_content = f"Проанализируй текст:\n\n{text}{already_desc}"

        response = self.client.messages.create(
            model=self.model,
            max_tokens=4096,
            system=[{
                "type": "text",
                "text": system_prompt,
                "cache_control": {"type": "ephemeral"},
            }],
            messages=[{"role": "user", "content": user_content}],
            output_config={
                "format": {
                    "type": "json_schema",
                    "schema": FINDINGS_SCHEMA,
                }
            },
        )

        text_block = next(
            (b.text for b in response.content if b.type == "text"), "{}"
        )
        data = json.loads(text_block)
        findings = data.get("findings", [])

        # Ensure source is set
        for f in findings:
            f["source"] = "deep"
            f.setdefault("section", "")
            f.setdefault("description", "")

        return findings
