from __future__ import annotations

from typing import Dict, List, Optional
from dataclasses import asdict

from core.tool import ToolBase, tool, tool_func
from core.memory import Finding


@tool("memory_write", "分段记忆写入")
class MemoryWriteTool(ToolBase):
    @tool_func(
        {
            "type": "object",
            "properties": {
                "segment_id": {"type": "string"},
                "topics": {"type": "array"},
                "review_output": {"type": "object"},
                "dependencies": {"type": "array"},
                "write_policy": {"type": "object"},
            },
            "required": ["segment_id", "topics", "review_output"],
        }
    )
    def run(self, segment_id: str, topics: List[str], review_output: Dict, dependencies: Optional[List[str]] = None, write_policy: Optional[Dict] = None) -> Dict:
        # 将审查输出转换为简化结构的 findings 写入 MemoryStore
        findings = review_output.get("findings", [])
        added: List[Dict] = []

        for f in findings:
            finding_id = str(f.get("id") or "")
            rule_title = f.get("rule_title") or ""
            issue = f.get("issue") or f.get("issue_description") or ""
            level = (f.get("level") or f.get("risk_level") or "M").upper()
            suggestion = f.get("suggestion") or ""
            result = f.get("result") or ""
            evs = list(f.get("evidence_quotes", []) or [])
            original_text = evs[0] if evs else (f.get("original_text") or "")

            try:
                finding_obj = Finding(
                    rule_title=rule_title,
                    segment_id=int(segment_id) if str(segment_id).isdigit() else 0,
                    original_text=original_text,
                    issue=issue,
                    risk_level=level,
                    suggestion=suggestion,
                    id=finding_id,
                    result=result,
                )
                store.add_finding(finding_obj)
                added.append(asdict(finding_obj))
            except Exception:
                # 保守处理：跳过格式异常项
                continue

        memory_id = "m_" + segment_id
        return {
            "memory_id": memory_id,
            "findings": added,
        }
