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91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
"""
Agent tools for CVE-KGRAG.

Five tools exposed to the agent:
1. search(query, collections, k, severity, year, is_in_kev) — unified Qdrant hybrid search (parallel)
2. explore_kg(node_id, node_label, hops)   — Neo4j graph traversal from any node label
3. find_similar_cves(cve_id, k)            — Neo4j CVE similarity scoring
4. translate_symptom(symptom_text)          — LLM + cheat-sheet: symptom → {techniques, cwes, keywords}
5. search_web(query)                        — optional web search (Tavily)

Tools are created via factories because they need runtime dependencies
(rag_system, graph_service, llm_client, cheat_sheet) injected at startup.
"""

from __future__ import annotations

import asyncio
import concurrent.futures
import logging
from typing import Any

from src.agents.agent_config import AGENT_DEFAULT_K, AGENT_SEARCH_TIMEOUT

logger = logging.getLogger(__name__)


def _format_search_results(results: list[dict], max_per_result: int = 300) -> str:
    if not results:
        return "No results found."
    lines = []
    for i, r in enumerate(results, 1):
        meta = r.get("metadata", {})
        cve_id = meta.get("cve_id", "")
        tech_id = meta.get("technique_id", "")
        capec_id = meta.get("capec_id", "")
        cwe_id = meta.get("cwe_id", "")
        ids = [x for x in [cve_id, tech_id, capec_id, cwe_id] if x]
        id_str = ids[0] if ids else r.get("id", "?")

        severity = meta.get("severity", "")
        cvss = meta.get("cvss_score", "")
        text = (r.get("text", "") or "")[:max_per_result]
        score = r.get("score", 0.0)

        meta_parts = []
        if severity:
            meta_parts.append(f"severity={severity}")
        if cvss:
            meta_parts.append(f"CVSS={cvss}")
        meta_str = f" ({', '.join(meta_parts)})" if meta_parts else ""

        lines.append(f"[{i}] {id_str}{meta_str} score={score:.3f}\n{text}")
    return "\n\n".join(lines)


def _search_single_collection(
    rag_system: Any, query: str, collection: str, k: int,
    filters: dict | None = None,
) -> list[dict]:
    """Search a single Qdrant collection (runs in thread pool for parallelism)."""
    try:
        return rag_system.search(query, n_results=k, collection=collection, filters=filters)
    except Exception as e:
        logger.warning("Search failed for %s: %s", collection, e)
        return []


def create_search_tool(rag_system: Any):
    """
    Create the unified search tool.

    Searches ALL requested collections in parallel via ThreadPoolExecutor.
    Merges and deduplicates results from all collections.
    """
    from langchain_core.tools import tool as lc_tool

    valid_collections = {"cve", "mitre", "capec", "cwe"}

    @lc_tool
    def search(
        query: str,
        collections: list[str] = ["cve"],
        k: int = AGENT_DEFAULT_K,
        severity: str | None = None,
        year: str | None = None,
        is_in_kev: bool | None = None,
    ) -> str:
        """Search CVE vulnerability knowledge bases across multiple collections in parallel.

        Available collections:
          'cve'   - CVE vulnerability entries (descriptions, CVSS scores, affected products)
          'mitre' - MITRE ATT&CK techniques (T-codes like T1059, procedures)
          'capec' - CAPEC attack patterns (CAPEC-IDs, attack vector descriptions)
          'cwe'   - CWE weakness types (CWE-IDs, weakness taxonomy)

        Use 'cve' alone for most queries. Add others when the user mentions
        techniques, attack patterns, or weakness types.

        Optional filters (apply to 'cve' collection only):
          severity  - CRITICAL / HIGH / MEDIUM / LOW
          year      - e.g. "2024"
          is_in_kev - True to restrict to Known Exploited Vulnerabilities
        """
        collections = [c for c in collections if c in valid_collections]
        if not collections:
            collections = ["cve"]

        filters: dict | None = None
        raw_filters = {
            "severity": severity,
            "year": year,
            "is_in_kev": is_in_kev,
        }
        active = {fk: fv for fk, fv in raw_filters.items() if fv is not None}
        if active:
            filters = active

        all_results: list[dict] = []

        if len(collections) == 1:
            all_results = list(_search_single_collection(rag_system, query, collections[0], k * 2, filters))
        else:
            with concurrent.futures.ThreadPoolExecutor(max_workers=len(collections)) as executor:
                futures = {
                    executor.submit(
                        _search_single_collection, rag_system, query, col, k * 2,
                        filters if col == "cve" else None,
                    ): col
                    for col in collections
                }
                try:
                    for future in concurrent.futures.as_completed(futures, timeout=AGENT_SEARCH_TIMEOUT):
                        col = futures[future]
                        try:
                            results = future.result()
                            all_results.extend(results)
                        except Exception as e:
                            logger.warning("Search failed for %s: %s", col, e)
                except concurrent.futures.TimeoutError:
                    logger.warning("Parallel search timed out after %.0fs — using partial results (%d)", AGENT_SEARCH_TIMEOUT, len(all_results))

        all_results.sort(key=lambda x: x.get("score", 0), reverse=True)
        unique = []
        seen = set()
        for r in all_results:
            rid = r.get("id", "")
            if rid not in seen:
                seen.add(rid)
                unique.append(r)

        return _format_search_results(unique[:k])

    return search


def create_explore_kg_tool(graph_service: Any):
    """
    Create the Neo4j knowledge graph explorer tool.

    Supports any node label as the traversal seed (CVE, CWE, Product, Technique,
    Tactic, CAPEC, Vendor), not just CVE. Falls back to empty string gracefully.
    """
    from langchain_core.tools import tool as lc_tool

    @lc_tool
    def explore_kg(node_id: str, node_label: str = "CVE", hops: int = 1) -> str:
        """Explore the Neo4j knowledge graph starting from any node.

        node_label must be one of: CVE, CWE, CAPEC, Technique, Tactic, Product, Vendor.

        Use when:
        - User asks "what CVEs relate to CVE-X"      → node_label="CVE"
        - User asks "CVEs affecting Apache Struts"    → node_label="Product"
        - User asks "CVEs mapped to T1190"            → node_label="Technique"
        - User asks "CVEs in tactic TA0001"           → node_label="Tactic"
        - User asks "CVEs with CWE-79 weakness"       → node_label="CWE"
        - User asks "CVEs using CAPEC-66 pattern"     → node_label="CAPEC"

        Returns empty string if no graph data is found.
        """
        if graph_service is None:
            return ""

        valid_labels = {"CVE", "CWE", "CAPEC", "Technique", "Tactic", "Product", "Vendor"}
        if node_label not in valid_labels:
            return f"Unknown node_label {node_label!r}. Must be one of: {', '.join(sorted(valid_labels))}"

        try:
            subgraph = graph_service.subgraph_from_nodes(
                [{"label": node_label, "id": node_id}], hops=hops
            )
            nodes = subgraph.get("nodes", [])
            edges = subgraph.get("edges", [])

            if not nodes and not edges:
                # Try cves_for_node as fallback (non-CVE seeds often need direct query)
                if node_label != "CVE":
                    cves = graph_service.cves_for_node(node_label, node_id, k=10)
                    if cves:
                        lines = [f"CVEs connected to {node_label} {node_id!r}:"]
                        for c in cves:
                            cvss = f" CVSS={c['cvss']}" if c.get("cvss") else ""
                            lines.append(f"  {c['id']}{cvss}")
                        return "\n".join(lines)
                return ""

            by_label: dict[str, list[str]] = {}
            for n in nodes:
                lbl = n.get("label", "Unknown")
                nid = n.get("id") or n.get("name") or "?"
                by_label.setdefault(lbl, []).append(str(nid))

            parts = [f"Knowledge Graph — {node_label} {node_id!r}:"]
            for lbl, ids in by_label.items():
                parts.append(f"  {lbl}: {', '.join(ids[:12])}")

            if edges:
                edge_summ: dict[str, int] = {}
                for e in edges:
                    rtype = e.get("type", "RELATED_TO")
                    edge_summ[rtype] = edge_summ.get(rtype, 0) + 1
                parts.append("Relationships: " + ", ".join(
                    f"{count}× {rtype}" for rtype, count in edge_summ.items()
                ))

            return "\n".join(parts)

        except Exception as e:
            logger.warning("KG explore failed for %s %s: %s", node_label, node_id, e)
            return ""

    return explore_kg


# Keep old name as alias for any external callers
create_traverse_kg_tool = create_explore_kg_tool


def create_web_search_tool():
    """
    Create the web search tool (optional, requires Tavily API key).

    Gracefully returns a message if not configured.
    """
    from langchain_core.tools import tool as lc_tool
    from src.agents.agent_config import WEB_SEARCH_ENABLED

    _tavily_available = False
    try:
        from langchain_community.tools.tavily_search import TavilySearchResults
        _tavily_available = True
    except ImportError:
        pass

    if not _tavily_available or not WEB_SEARCH_ENABLED:
        @lc_tool
        def search_web(query: str) -> str:
            """Search the web for recent exploit/POC information. Currently disabled."""
            return "Web search is not configured. Set WEB_SEARCH_ENABLED=true and install langchain-community with Tavily API key."
        return search_web

    @lc_tool
    def search_web(query: str) -> str:
        """Search the web for recent exploits, POC code, or latest vulnerability news.

        Use when the user asks about exploits, proof-of-concept code, zero-day
        vulnerabilities, or very recent CVEs not yet in the local database.
        """
        try:
            tool = TavilySearchResults(max_results=3, search_depth="advanced")
            results = tool.invoke(query)
            lines = ["[Web search results:]"]
            for i, r in enumerate(results, 1):
                lines.append(f"[{i}] {r.get('title', '?')}\n{r.get('content', '')[:300]}\n{r.get('url', '')}")
            return "\n\n".join(lines)
        except Exception as e:
            logger.warning("Web search failed: %s", e)
            return f"Web search failed: {e}"

    return search_web


def create_find_similar_cves_tool(graph_service: Any):
    """
    Create the similar-CVE lookup tool.

    Queries Neo4j for CVEs sharing CWE / product / tactic with the given CVE.
    Returns empty string when graph_service is unavailable or no results found.
    """
    from langchain_core.tools import tool as lc_tool

    @lc_tool
    def find_similar_cves(cve_id: str, k: int = 5) -> str:
        """Find CVEs similar to the given one based on shared weaknesses, affected products, or tactics.

        Use when the user asks:
        - "what CVEs are similar to CVE-X?"
        - "CVEs related to CVE-X"
        - "find vulnerabilities like CVE-X"

        Returns empty string if no graph data is available.
        """
        if graph_service is None:
            return ""
        try:
            results = graph_service.similar_cves(cve_id, k=k)
            if not results:
                return f"No similar CVEs found for {cve_id} in the knowledge graph."
            lines = [f"CVEs similar to {cve_id}:"]
            for r in results:
                lines.append(
                    f"  - {r['cve_id']} (via shared {r['shared_type']}, score={r['score']})"
                )
            return "\n".join(lines)
        except Exception as e:
            logger.warning("similar_cves failed for %s: %s", cve_id, e)
            return ""

    return find_similar_cves


def create_translate_symptom_tool(llm_client: Any, cheat_sheet: Any = None):
    """
    Create the symptom-to-CTI-entity translation tool.

    Uses cheat-sheet hints for grounding + LLM to map free-text observations
    (log lines, behavioral symptoms) to MITRE techniques, CWE IDs, and keywords.
    Returns JSON string: {"techniques": [...], "cwes": [...], "keywords": [...]}.
    """
    import json as _json
    from langchain_core.tools import tool as lc_tool
    from src.agents.prompts import TRANSLATE_SYMPTOM_PROMPT
    from src.agents.tracing import traced_llm_call

    def _parse_json_safely(text: str, default: dict) -> dict:
        import re
        text = (text or "").strip()
        for prefix in ("```json", "```"):
            if text.startswith(prefix):
                text = text[len(prefix):]
        if text.endswith("```"):
            text = text[:-3]
        text = text.strip()
        try:
            return _json.loads(text)
        except _json.JSONDecodeError:
            try:
                m = re.search(r'\{.*\}', text, re.DOTALL)
                if m:
                    return _json.loads(m.group())
            except (_json.JSONDecodeError, AttributeError):
                pass
            return default

    @lc_tool
    def translate_symptom(symptom_text: str) -> str:
        """Translate a free-text security symptom or log observation into MITRE techniques,
        CWE IDs, and search keywords.

        Use FIRST when the user describes observed behavior without mentioning a CVE-ID,
        product name, or CWE-ID. Examples:
        - "process spawning powershell.exe with base64-encoded args from outlook"
        - "server files are encrypted with ransom note left behind"
        - "unauthenticated read of /etc/passwd via crafted URL parameter"

        Returns JSON: {"techniques": ["T1059", ...], "cwes": ["CWE-78", ...], "keywords": [...]}
        Use the returned techniques/CWEs as inputs to explore_kg; use keywords for search().
        """
        if llm_client is None:
            return '{"techniques": [], "cwes": [], "keywords": []}'

        hint_block = ""
        if cheat_sheet is not None:
            try:
                hints = cheat_sheet.entity_to_hints(symptom_text)
                hint_block = cheat_sheet.render_hint_block(hints) or ""
            except Exception:
                pass

        prompt = TRANSLATE_SYMPTOM_PROMPT.format(
            symptom=symptom_text,
            hints=hint_block or "(no taxonomy hints available)",
        )
        try:
            with traced_llm_call(
                llm_client, prompt, "translate_symptom",
                system_prompt="Answer in JSON only.", max_tokens=300,
            ) as gen:
                raw = gen()
            parsed = _parse_json_safely(raw, {"techniques": [], "cwes": [], "keywords": []})
            return _json.dumps(parsed)
        except Exception as e:
            logger.warning("translate_symptom failed: %s", e)
            return '{"techniques": [], "cwes": [], "keywords": []}'

    return translate_symptom


def create_agent_tools(
    rag_system: Any,
    graph_service: Any,
    llm_client: Any = None,
    cheat_sheet: Any = None,
) -> list:
    """Create all agent tools with runtime dependencies injected."""
    tools = [
        create_search_tool(rag_system),
        create_explore_kg_tool(graph_service),
        create_find_similar_cves_tool(graph_service),
    ]
    if llm_client is not None:
        tools.append(create_translate_symptom_tool(llm_client, cheat_sheet))
    tools.append(create_web_search_tool())
    return tools