File size: 27,828 Bytes
27f6252
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
#!/usr/bin/env python3
"""
Neo4j Graph Service — replaces NetworkX graph builder.

Responsibilities
----------------
1. bulk_load()  — load all KG JSON files into Neo4j in batched transactions.
2. similar_cves() — find CVEs related by shared CWE / product / vendor.
3. subgraph_for_cves() — expand a set of CVE IDs by N hops for RAG context.
4. (optional) centrality_scores() — PageRank via GDS for ranked context.

Run as CLI to do the bulk load:
    python -m src.constructors.neo4j_graph_service --bulk-load
    python -m src.constructors.neo4j_graph_service --similar CVE-2021-44228
    python -m src.constructors.neo4j_graph_service --stats
"""

from __future__ import annotations

import argparse
import json
import logging
import sys
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple

from neo4j import GraphDatabase, Session

project_root = Path(__file__).parent.parent.parent
sys.path.insert(0, str(project_root))

from config import Config
from src.generators.rag_config import NEO4J_URI, NEO4J_USER, NEO4J_PASSWORD

logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
logger = logging.getLogger(__name__)

_BATCH = 10_000   # rows per Neo4j transaction


class Neo4jGraphService:
    """
    Bulk-load KG JSON → Neo4j and expose graph query helpers.
    Connects on construction; call .close() when done.
    """

    def __init__(
        self,
        uri: str  = NEO4J_URI,
        user: str = NEO4J_USER,
        pwd: str  = NEO4J_PASSWORD,
    ) -> None:
        self.driver = GraphDatabase.driver(uri, auth=(user, pwd))
        self.config = Config()
        self.kg_dir = self.config.knowledge_base_dir / "knowledge_graph"

    def close(self) -> None:
        self.driver.close()

    def __enter__(self) -> "Neo4jGraphService":
        return self

    def __exit__(self, *_: Any) -> None:
        self.close()

    # ── schema ────────────────────────────────────────────────────────────────

    def create_constraints(self) -> None:
        """Unique constraints guarantee idempotent MERGE."""
        constraints = [
            ("CVE",       "id"),
            ("Product",   "name"),
            ("Vendor",    "name"),
            ("CWE",       "id"),
            ("CAPEC",     "id"),
            ("Technique", "id"),
            ("Tactic",    "id"),
        ]
        with self.driver.session() as s:
            for label, prop in constraints:
                try:
                    s.run(
                        f"CREATE CONSTRAINT IF NOT EXISTS "
                        f"FOR (n:{label}) REQUIRE n.{prop} IS UNIQUE"
                    )
                except Exception as e:
                    logger.warning(f"Constraint {label}.{prop}: {e}")
        logger.info("Constraints ensured.")

    # ── bulk loader ───────────────────────────────────────────────────────────

    def bulk_load(self) -> None:
        """Load all JSON KG files into Neo4j. Idempotent (uses MERGE)."""
        logger.info("Starting Neo4j bulk load …")
        self.create_constraints()

        self._load_cve_nodes()
        self._load_product_nodes()
        self._load_vendor_nodes()
        self._load_cwe_nodes()
        self._load_capec_nodes()
        self._load_technique_nodes()
        self._load_tactic_nodes()

        self._load_rels("cve_cwe_relationships.json",           self._upsert_cve_cwe)
        self._load_rels("cve_product_relationships.json",       self._upsert_cve_product)
        self._load_rels("cve_capec_relationships.json",         self._upsert_cve_capec)
        self._load_rels("cve_mitre_technique_relationships.json",self._upsert_cve_technique)
        self._load_rels("cve_mitre_tactic_relationships.json",  self._upsert_cve_tactic)
        self._load_rels("product_vendor_relationships.json",    self._upsert_product_vendor)

        logger.info("Bulk load complete.")
        self._log_counts()

    # ── node loaders ──────────────────────────────────────────────────────────

    def _load_cve_nodes(self) -> None:
        data = self._read_json("cves_nodes.json")
        rows = list(data.values()) if isinstance(data, dict) else data
        logger.info(f"Loading {len(rows):,} CVE nodes …")
        cypher = """
        UNWIND $rows AS r
        MERGE (c:CVE {id: r.id})
        SET c.title             = r.title,
            c.description       = r.description,
            c.source            = r.source,
            c.published_date    = r.published_date,
            c.last_modified     = r.last_modified_date,
            c.cvss_v3_score     = r.cvss_v3_score,
            c.cvss_v3_severity  = r.cvss_v3_severity,
            c.cvss_v3_vector    = r.cvss_v3_vector,
            c.attack_vector     = r.attack_vector,
            c.attack_complexity = r.attack_complexity,
            c.privileges_required = r.privileges_required,
            c.user_interaction  = r.user_interaction,
            c.scope             = r.scope,
            c.conf_impact       = r.conf_impact,
            c.integ_impact      = r.integ_impact,
            c.avail_impact      = r.avail_impact,
            c.cvss_v2_score     = r.cvss_v2_score,
            c.cvss_v2_vector    = r.cvss_v2_vector,
            c.is_in_kev         = r.is_in_kev,
            c.exploitdb_count   = r.exploitdb_count,
            c.tags              = r.tags
        """
        def _norm(r: Dict[str, Any]) -> Dict[str, Any]:
            cvss3 = r.get("cvss_v3") or {}
            cvss2 = r.get("cvss_v2") or {}
            # Use prose description (first line of content if available)
            raw_desc = r.get("content", r.get("description", "")) or ""
            prose = raw_desc.split("\n")[0].strip()
            # Build a real title from the first sentence of the description
            title = prose[:120] if prose else r.get("id", "")
            return {
                "id":                r.get("id", ""),
                "title":             title,
                "description":       prose,
                "source":            r.get("source", ""),
                "published_date":    r.get("published_date", ""),
                "last_modified_date":r.get("last_modified_date", ""),
                "cvss_v3_score":     cvss3.get("base_score"),
                "cvss_v3_severity":  cvss3.get("base_severity", ""),
                "cvss_v3_vector":    cvss3.get("vector_string", ""),
                "attack_vector":     cvss3.get("attack_vector", ""),
                "attack_complexity": cvss3.get("attack_complexity", ""),
                "privileges_required": cvss3.get("privileges_required", ""),
                "user_interaction":  cvss3.get("user_interaction", ""),
                "scope":             cvss3.get("scope", ""),
                "conf_impact":       cvss3.get("confidentiality_impact", ""),
                "integ_impact":      cvss3.get("integrity_impact", ""),
                "avail_impact":      cvss3.get("availability_impact", ""),
                "cvss_v2_score":     cvss2.get("base_score"),
                "cvss_v2_vector":    cvss2.get("vector_string", ""),
                "is_in_kev":         bool(r.get("is_in_kev", False)),
                "exploitdb_count":   r.get("exploitdb_correlations_count", 0) or 0,
                "tags":              r.get("tags") or [],
            }
        self._batch_write(cypher, [_norm(r) for r in rows])

    def _load_product_nodes(self) -> None:
        data = self._read_json("products_nodes.json")
        rows = list(data.values()) if isinstance(data, dict) else data
        logger.info(f"Loading {len(rows):,} Product nodes …")
        cypher = """
        UNWIND $rows AS r
        MERGE (p:Product {name: r.name})
        SET p.vendor            = r.vendor,
            p.display_name      = r.display_name,
            p.category          = r.category,
            p.criticality_score = r.criticality_score
        """
        self._batch_write(cypher, rows)

    def _load_vendor_nodes(self) -> None:
        data = self._read_json("vendors_nodes.json")
        rows = list(data.values()) if isinstance(data, dict) else data
        logger.info(f"Loading {len(rows):,} Vendor nodes …")
        cypher = """
        UNWIND $rows AS r
        MERGE (v:Vendor {name: r.name})
        """
        # vendors_nodes may store as {vendor_name: {name:..., ...}}
        norm_rows = []
        for r in rows:
            norm_rows.append({"name": r.get("name", r.get("vendor", ""))})
        self._batch_write(cypher, norm_rows)

    def _load_cwe_nodes(self) -> None:
        data = self._read_json("cwes_nodes.json")
        rows = list(data.values()) if isinstance(data, dict) else data
        logger.info(f"Loading {len(rows):,} CWE nodes …")

        # Enrich with real names + descriptions from cwe_chunks.json if available
        cwe_enrichment: Dict[str, Dict[str, str]] = {}
        cwe_chunks_path = (
            self.config.knowledge_base_dir / "rag_exports" / "cwe_chunks.json"
        )
        if cwe_chunks_path.exists():
            try:
                with open(cwe_chunks_path, encoding="utf-8") as f:
                    cwe_chunks = json.load(f)
                for c in cwe_chunks:
                    p = c.get("payload", {})
                    cid = p.get("cwe_id", "")
                    if cid:
                        cwe_enrichment[cid] = {
                            "name":        p.get("name", ""),
                            "description": c.get("text", "")[:500],
                        }
                logger.info(f"  CWE enrichment loaded: {len(cwe_enrichment)} entries")
            except Exception as e:
                logger.warning(f"  Could not load CWE enrichment: {e}")

        cypher = """
        UNWIND $rows AS r
        MERGE (w:CWE {id: r.id})
        SET w.name        = r.name,
            w.description = r.description,
            w.vuln_count  = r.vulnerability_count
        """

        def _norm(r: Dict[str, Any]) -> Dict[str, Any]:
            cid = r.get("id", "")
            enriched = cwe_enrichment.get(cid, {})
            raw_name = r.get("name", "")
            # Strip verbose prefix "Common Weakness Enumeration CWE-XXX" → real name
            clean_name = (
                enriched.get("name")
                or raw_name.replace("Common Weakness Enumeration ", "").strip()
                or cid
            )
            return {
                "id":               cid,
                "name":             clean_name,
                "description":      enriched.get("description", ""),
                "vulnerability_count": r.get("vulnerability_count", 0),
            }

        self._batch_write(cypher, [_norm(r) for r in rows])

    def _load_capec_nodes(self) -> None:
        data = self._read_json("capecs_nodes.json")
        rows = list(data.values()) if isinstance(data, dict) else data
        logger.info(f"Loading {len(rows):,} CAPEC nodes …")
        cypher = """
        UNWIND $rows AS r
        MERGE (a:CAPEC {id: r.id})
        SET a.name = r.name
        """
        self._batch_write(cypher, rows)

    def _load_technique_nodes(self) -> None:
        data = self._read_json("mitre_techniques_nodes.json")
        rows = list(data.values()) if isinstance(data, dict) else data
        logger.info(f"Loading {len(rows):,} Technique nodes …")

        # Load real names + descriptions from CTI technique JSON files
        cti_dir = self.config.cti_docs_dir / "attack_techniques"
        technique_enrichment: Dict[str, Dict[str, str]] = {}
        if cti_dir.exists():
            for jf in cti_dir.glob("*.json"):
                try:
                    with open(jf, encoding="utf-8") as f:
                        doc = json.load(f)
                    tid = doc.get("id", "")
                    if tid:
                        technique_enrichment[tid] = {
                            "name":        doc.get("title", ""),
                            "description": (doc.get("content") or "")[:400],
                            "tactics":     ", ".join(doc.get("tactics", [])),
                        }
                except Exception:
                    pass
            logger.info(f"  Technique enrichment loaded: {len(technique_enrichment)} entries")

        cypher = """
        UNWIND $rows AS r
        MERGE (t:Technique {id: r.id})
        SET t.name        = r.name,
            t.description = r.description,
            t.tactics     = r.tactics,
            t.vuln_count  = r.vulnerability_count
        """

        def _norm(r: Dict[str, Any]) -> Dict[str, Any]:
            tid = r.get("id", "")
            enriched = technique_enrichment.get(tid, {})
            raw_name = r.get("name", r.get("title", ""))
            clean_name = (
                enriched.get("name")
                or raw_name.replace("MITRE ATT&CK Technique ", "").strip()
                or tid
            )
            return {
                "id":               tid,
                "name":             clean_name,
                "description":      enriched.get("description", ""),
                "tactics":          enriched.get("tactics", ""),
                "vulnerability_count": r.get("vulnerability_count", 0),
            }

        self._batch_write(cypher, [_norm(r) for r in rows])

    def _load_tactic_nodes(self) -> None:
        data = self._read_json("mitre_tactics_nodes.json")
        rows = list(data.values()) if isinstance(data, dict) else data
        logger.info(f"Loading {len(rows):,} Tactic nodes …")
        cypher = """
        UNWIND $rows AS r
        MERGE (t:Tactic {id: r.id})
        SET t.name       = r.name,
            t.vuln_count = r.vulnerability_count
        """

        def _norm(r: Dict[str, Any]) -> Dict[str, Any]:
            raw_name = r.get("name", r.get("title", ""))
            # Strip verbose prefix "MITRE ATT&CK Tactic TXXX" → real name
            clean_name = raw_name.replace("MITRE ATT&CK Tactic ", "").strip() or r.get("id", "")
            return {
                "id":               r.get("id", ""),
                "name":             clean_name,
                "vulnerability_count": r.get("vulnerability_count", 0),
            }

        self._batch_write(cypher, [_norm(r) for r in rows])

    # ── relationship loaders ──────────────────────────────────────────────────

    def _load_rels(self, filename: str, handler) -> None:
        path = self.kg_dir / filename
        if not path.exists():
            logger.warning(f"Relationship file not found: {filename}")
            return
        with open(path, encoding="utf-8") as f:
            rows = json.load(f)
        logger.info(f"Loading {len(rows):,} {filename} …")
        handler(rows)

    def _upsert_cve_cwe(self, rows: List[Dict[str, Any]]) -> None:
        cypher = """
        UNWIND $rows AS r
        MATCH (c:CVE {id: r.cve_id}), (w:CWE {id: r.cwe_id})
        MERGE (c)-[:HAS_WEAKNESS]->(w)
        """
        self._batch_write(cypher, rows)

    def _upsert_cve_product(self, rows: List[Dict[str, Any]]) -> None:
        cypher = """
        UNWIND $rows AS r
        MATCH (c:CVE {id: r.cve_id}), (p:Product {name: r.product_name})
        MERGE (c)-[:AFFECTS]->(p)
        """
        self._batch_write(cypher, rows)

    def _upsert_cve_capec(self, rows: List[Dict[str, Any]]) -> None:
        cypher = """
        UNWIND $rows AS r
        MATCH (c:CVE {id: r.cve_id}), (a:CAPEC {id: r.capec_id})
        MERGE (c)-[:USES_PATTERN]->(a)
        """
        norm = [{"cve_id": r.get("cve_id", ""), "capec_id": r.get("capec_id", "")} for r in rows]
        self._batch_write(cypher, norm)

    def _upsert_cve_technique(self, rows: List[Dict[str, Any]]) -> None:
        cypher = """
        UNWIND $rows AS r
        MATCH (c:CVE {id: r.cve_id}), (t:Technique {id: r.technique_id})
        MERGE (c)-[:IMPLEMENTS_TECHNIQUE]->(t)
        """
        norm = [{"cve_id": r.get("cve_id", ""), "technique_id": r.get("technique_id", "")} for r in rows]
        self._batch_write(cypher, norm)

    def _upsert_cve_tactic(self, rows: List[Dict[str, Any]]) -> None:
        cypher = """
        UNWIND $rows AS r
        MATCH (c:CVE {id: r.cve_id}), (t:Tactic {id: r.tactic_id})
        MERGE (c)-[:MAPPED_TO_TACTIC]->(t)
        """
        norm = [{"cve_id": r.get("cve_id", ""), "tactic_id": r.get("tactic_id", "")} for r in rows]
        self._batch_write(cypher, norm)

    def _upsert_product_vendor(self, rows: List[Dict[str, Any]]) -> None:
        cypher = """
        UNWIND $rows AS r
        MATCH (p:Product {name: r.product_name}), (v:Vendor {name: r.vendor_name})
        MERGE (p)-[:MANUFACTURED_BY]->(v)
        """
        norm = [{"product_name": r.get("product_name", r.get("product", "")),
                 "vendor_name":  r.get("vendor_name",  r.get("vendor", ""))} for r in rows]
        self._batch_write(cypher, norm)

    # ── query API ─────────────────────────────────────────────────────────────

    def similar_cves(self, cve_id: str, k: int = 10) -> List[Dict[str, Any]]:
        """
        Find CVEs related to cve_id by shared CWE, product, or tactic.
        Returns list of {cve_id, shared_type, score}.
        """
        cypher = """
        MATCH (src:CVE {id: $cve_id})
        CALL {
          WITH src
          MATCH (src)-[:HAS_WEAKNESS]->(w:CWE)<-[:HAS_WEAKNESS]-(other:CVE)
          WHERE other.id <> $cve_id
          RETURN other.id AS cve_id, 'cwe' AS shared_type, count(w) AS cnt
          UNION
          WITH src
          MATCH (src)-[:AFFECTS]->(p:Product)<-[:AFFECTS]-(other:CVE)
          WHERE other.id <> $cve_id
          RETURN other.id AS cve_id, 'product' AS shared_type, count(p) AS cnt
          UNION
          WITH src
          MATCH (src)-[:MAPPED_TO_TACTIC]->(t:Tactic)<-[:MAPPED_TO_TACTIC]-(other:CVE)
          WHERE other.id <> $cve_id
          RETURN other.id AS cve_id, 'tactic' AS shared_type, count(t) AS cnt
        }
        RETURN cve_id, shared_type, sum(cnt) AS score
        ORDER BY score DESC
        LIMIT $k
        """
        with self.driver.session() as s:
            result = s.run(cypher, cve_id=cve_id, k=k)
            return [{"cve_id": r["cve_id"], "shared_type": r["shared_type"], "score": r["score"]}
                    for r in result]

    def subgraph_for_cves(self, cve_ids: List[str], hops: int = 1) -> Dict[str, Any]:
        """Backward-compat wrapper — seed subgraph from CVE IDs."""
        return self.subgraph_from_nodes(
            [{"label": "CVE", "id": cid} for cid in cve_ids], hops=hops
        )

    # ── label-agnostic KG API ─────────────────────────────────────────────────

    _LABEL_KEY: Dict[str, str] = {
        "CVE": "id", "CWE": "id", "CAPEC": "id",
        "Technique": "id", "Tactic": "id",
        "Product": "name", "Vendor": "name",
    }

    _LABEL_TO_CVE_REL: Dict[str, Optional[str]] = {
        "CWE":       "HAS_WEAKNESS",
        "CAPEC":     "USES_PATTERN",
        "Technique": "IMPLEMENTS_TECHNIQUE",
        "Tactic":    "MAPPED_TO_TACTIC",
        "Product":   "AFFECTS",
        "Vendor":    None,   # handled via Product hop
    }

    def lookup_by_label(self, label: str, query: str, k: int = 5) -> List[Dict[str, Any]]:
        """
        Fuzzy + exact match a node by label.

        Returns [{id, name, props}]. Label must be in _LABEL_KEY whitelist.
        """
        if label not in self._LABEL_KEY:
            logger.warning("lookup_by_label: unknown label %r", label)
            return []
        key = self._LABEL_KEY[label]
        cypher = f"""
        MATCH (n:{label})
        WHERE toLower(n.{key}) = toLower($q)
           OR toLower(n.{key}) CONTAINS toLower($q)
        RETURN coalesce(n.id, n.name) AS id,
               coalesce(n.name, n.id) AS name,
               properties(n)         AS props
        LIMIT $k
        """
        with self.driver.session() as s:
            result = s.run(cypher, q=query, k=k)
            return [{"id": r["id"], "name": r["name"], "props": dict(r["props"])} for r in result]

    def cves_for_node(self, label: str, node_id: str, k: int = 10) -> List[Dict[str, Any]]:
        """
        Given a non-CVE seed (Product, CWE, Technique, Tactic, CAPEC, Vendor),
        return connected CVEs ordered by CVSS score desc.
        """
        if label not in self._LABEL_TO_CVE_REL:
            return []
        key = self._LABEL_KEY.get(label, "id")
        rel  = self._LABEL_TO_CVE_REL[label]

        if label == "Vendor":
            cypher = f"""
            MATCH (v:Vendor)-[:MANUFACTURED_BY]-(p:Product)-[:AFFECTS]-(c:CVE)
            WHERE v.name = $nid
            RETURN DISTINCT c.id AS id, c.cvss_v3_score AS cvss, c.description AS desc
            ORDER BY cvss DESC LIMIT $k
            """
        elif rel:
            cypher = f"""
            MATCH (n:{label})-[:{rel}]-(c:CVE)
            WHERE n.{key} = $nid
            RETURN c.id AS id, c.cvss_v3_score AS cvss, c.description AS desc
            ORDER BY cvss DESC LIMIT $k
            """
        else:
            return []

        with self.driver.session() as s:
            return [
                {"id": r["id"], "cvss": r["cvss"], "description": r["desc"]}
                for r in s.run(cypher, nid=node_id, k=k)
            ]

    def subgraph_from_nodes(self, seeds: List[Dict[str, str]], hops: int = 1) -> Dict[str, Any]:
        """
        General subgraph expansion from heterogeneous seeds [{label, id}, ...].

        Replaces the CVE-only subgraph_for_cves. Expands each seed label
        separately and merges results. Label must be in _LABEL_KEY whitelist.
        """
        hops = max(1, int(hops))
        by_label: Dict[str, List[str]] = {}
        for s in seeds:
            lbl = s.get("label", "")
            if lbl in self._LABEL_KEY:
                by_label.setdefault(lbl, []).append(s["id"])

        all_nodes: List[Dict] = []
        all_edges: List[Dict] = []

        with self.driver.session() as session:
            for label, ids in by_label.items():
                key = self._LABEL_KEY[label]
                cypher = f"""
                MATCH path = (seed:{label})-[*1..{hops}]-(n)
                WHERE seed.{key} IN $ids
                UNWIND nodes(path) AS node
                UNWIND relationships(path) AS rel
                RETURN DISTINCT
                    labels(node)[0]                           AS node_label,
                    coalesce(node.id, node.name)              AS node_id,
                    node.name                                 AS node_name,
                    type(rel)                                 AS rel_type,
                    coalesce(startNode(rel).id, startNode(rel).name) AS rel_start,
                    coalesce(endNode(rel).id,   endNode(rel).name)   AS rel_end
                LIMIT 500
                """
                for r in session.run(cypher, ids=ids):
                    all_nodes.append({
                        "label": r["node_label"],
                        "id":    r["node_id"],
                        "name":  r["node_name"],
                    })
                    all_edges.append({
                        "type":  r["rel_type"],
                        "start": r["rel_start"],
                        "end":   r["rel_end"],
                    })

        # Dedup
        seen_n: set = set()
        seen_e: set = set()
        nodes = [n for n in all_nodes if (n["label"], n["id"]) not in seen_n
                 and not seen_n.add((n["label"], n["id"]))]   # type: ignore[func-returns-value]
        edges = [e for e in all_edges if (e["type"], e["start"], e["end"]) not in seen_e
                 and not seen_e.add((e["type"], e["start"], e["end"]))]   # type: ignore[func-returns-value]

        return {"nodes": nodes, "edges": edges}

    # ── stats ─────────────────────────────────────────────────────────────────

    def get_stats(self) -> Dict[str, int]:
        labels = ["CVE", "Product", "Vendor", "CWE", "CAPEC", "Technique", "Tactic"]
        stats: Dict[str, int] = {}
        with self.driver.session() as s:
            for label in labels:
                result = s.run(f"MATCH (n:{label}) RETURN count(n) AS cnt")
                stats[label] = result.single()["cnt"]
        return stats

    def _log_counts(self) -> None:
        stats = self.get_stats()
        for label, cnt in stats.items():
            logger.info(f"  {label}: {cnt:,}")

    # ── internal ──────────────────────────────────────────────────────────────

    def _read_json(self, filename: str) -> Any:
        path = self.kg_dir / filename
        if not path.exists():
            logger.warning(f"File not found: {path}")
            return {}
        logger.info(f"  Reading {filename} ({path.stat().st_size / 1e6:.0f} MB) …")
        with open(path, encoding="utf-8") as f:
            return json.load(f)

    def _batch_write(self, cypher: str, rows: List[Dict[str, Any]]) -> None:
        total = len(rows)
        with self.driver.session() as s:
            for start in range(0, total, _BATCH):
                batch = rows[start : start + _BATCH]
                s.run(cypher, rows=batch)
                if (start + _BATCH) % (10 * _BATCH) == 0:
                    logger.info(f"    … {start + _BATCH:,} / {total:,}")


# ─────────────────────────────────────────────────────────────────────────────
# CLI
# ─────────────────────────────────────────────────────────────────────────────

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Neo4j Graph Service")
    parser.add_argument("--bulk-load", action="store_true", help="Load KG JSON → Neo4j")
    parser.add_argument("--similar",   type=str,           help="Find CVEs similar to given CVE-ID")
    parser.add_argument("--k",         type=int, default=10)
    parser.add_argument("--stats",     action="store_true")
    args = parser.parse_args()

    with Neo4jGraphService() as svc:
        if args.bulk_load:
            svc.bulk_load()
        elif args.similar:
            results = svc.similar_cves(args.similar, k=args.k)
            print(f"\nCVEs similar to {args.similar}:")
            for r in results:
                print(f"  {r['cve_id']:25s}  ({r['shared_type']:10s})  score={r['score']}")
        elif args.stats:
            stats = svc.get_stats()
            print("\nNeo4j node counts:")
            for label, cnt in stats.items():
                print(f"  {label:12s}: {cnt:,}")
        else:
            parser.print_help()