from __future__ import annotations

from typing import Dict, List, Optional

from core.tool import ToolBase, tool, tool_func
from tools.shared import store, limit_list


@tool("full_read", "分段原文读取/摘录")
class FullReadTool(ToolBase):
    @tool_func(
        {
            "type": "object",
            "properties": {
                "target": {"type": "object"},
                "need_focus": {"type": "array"},
                "return_snippets": {"type": "boolean"},
            },
            "required": ["target"],
        }
    )
    def run(self, target: Dict, need_focus: Optional[List[str]] = None, return_snippets: bool = True) -> Dict:
        seg_id = (target or {}).get("id") or (target or {}).get("segment_id") or ""
        mem = store.get(seg_id) if seg_id else None

        full_text = " ".join(mem.evidence_quotes) if mem and mem.evidence_quotes else ""
        if not full_text:
            full_text = "(原文未存储，建议在调用端提供全文或将原文写入 MemoryStore)"

        focus = need_focus or []
        snippets: List[str] = []
        if return_snippets and mem:
            for kw in focus:
                for q in mem.evidence_quotes:
                    if kw and kw in q:
                        snippets.append(q)
            if not snippets:
                for kw in focus:
                    for s in mem.summary.structured:
                        if kw and kw in s:
                            snippets.append(s)
        snippets = limit_list(list(dict.fromkeys(snippets)), 5)

        return {
            "target": {"type": "segment", "id": seg_id},
            "full_text": full_text,
            "highlighted_snippets": snippets,
        }
