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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
"""
TempBench Builder
==========================
Constructs a 10K-question multi-hop temporal QA benchmark (see the TempBench paper).

Implements the full 6-stage pipeline:
  1. Question generation from KG triples and templates
  2. Composability filtering (validate temporal consistency)
  3. Answer uniqueness filtering (discard ambiguous questions)
  4. MinHash deduplication (Jaccard similarity threshold)
  5. Subgraph construction (S_star, S_dist, S_stale)
  6. Train/dev/test split (stratified by complexity)

Output: JSONL benchmark with one question per line, including supporting subgraphs.

Usage:
    python build_benchmark.py --kg_path kg.json --output_dir ./benchmark/ --target_n 10000

"""

from __future__ import annotations

import argparse
import hashlib
import json
import math
import random
import sys
from collections import defaultdict
from dataclasses import dataclass, asdict
from pathlib import Path
from typing import Dict, List, Optional, Set, Tuple

from indexer import (
    TemporalKGIndexer,
    Triple,
    ValidityWindow,
)

# ---------------------------------------------------------------------------
# Question generation templates
# ---------------------------------------------------------------------------

QUESTION_TEMPLATES = {
    # The TempBench paper cites the TimelineKGQA taxonomy for four operator types.
    # Each operator takes a compositional chain "path" (= anchor + hop
    # relations, joined by "'s") and attaches an operator-specific temporal
    # qualifier. See benchmark-design-decisions.md §1 for semantics.
    "point_in_time": [
        "In {year}, what was the {final_relation} of {path}?",
        "What was the {final_relation} of {path} in {year}?",
        "{path}'s {final_relation} in {year} was?",
    ],
    "before_after": [
        "Who was the {final_relation} of {path} {qualifier} {sibling}?",
        "{qualifier_cap} {sibling}, who was the {final_relation} of {path}?",
    ],
    "interval": [
        "In what year was the {final_relation} of {path} equal to {terminal}?",
        "When was {terminal} the {final_relation} of {path}?",
    ],
    "sequence": [
        "After {ref_subject} {ref_relation} {ref_object}, what was the {final_relation} of {path}?",
        "What was the {final_relation} of {path} after {ref_subject} {ref_relation} {ref_object}?",
    ],
}


def _render_composition_path(anchor: str, relations: List[str]) -> str:
    """
    Render the nested possessive prefix for compositional multi-hop questions.

    Example:
        anchor = "Obama", relations = ["spouse", "country"]
        returns: "Obama's spouse's country"
    Used as the {path} placeholder for the last-but-one hop; the final
    relation becomes the {final_relation} placeholder.
    """
    parts = [anchor] + relations
    return "'s ".join(parts)

# ---------------------------------------------------------------------------
# Data structures
# ---------------------------------------------------------------------------

@dataclass
class Candidate:
    """An intermediate candidate question before filtering."""
    id: str
    question: str
    t_query: float
    answer: str
    complexity: str  # "1hop", "2hop", "3plus"
    operator_type: str  # "point_in_time", "before_after", "interval", "sequence"
    question_type: str  # "explicit", "implicit", "ordinal"
    gold_chain: List[Triple]


@dataclass
class BenchmarkQuestion:
    """A final, fully-validated benchmark question."""
    id: str
    question: str
    t_query: float
    answer: str
    complexity: str
    operator_type: str
    question_type: str
    S_star: List[Dict]  # Gold chain
    S_dist: List[Dict]  # Distractor chain
    S_stale: List[Dict]  # Stale-fact chain
    split: str  # "train", "dev", "test"

    def to_jsonl_dict(self) -> Dict:
        """Convert to dict for JSONL serialization."""
        return {
            "id": self.id,
            "question": self.question,
            "t_query": self.t_query,
            "answer": self.answer,
            "complexity": self.complexity,
            "operator_type": self.operator_type,
            "question_type": self.question_type,
            "S_star": self.S_star,
            "S_dist": self.S_dist,
            "S_stale": self.S_stale,
            "split": self.split,
        }


# ---------------------------------------------------------------------------
# Stage 1: Question generation (fallback mode)
# ---------------------------------------------------------------------------

class QuestionGenerator:
    """
    Generates candidate questions from KG triples using templates.
    Fallback mode when TimelineKGQA is not available.
    """

    def __init__(self, indexer: TemporalKGIndexer, seed: int = 42):
        self.indexer = indexer
        self.rng = random.Random(seed)
        self.triples = indexer._all_triples
        self.candidate_id_counter = 0
        # Collect all actual timestamps for point-in-time TKGs (t_start == t_end)
        self._timestamps: List[float] = sorted(
            {t.t_start for t in self.triples}
        )
        # tkgl-smallpedia is 100% point-in-time; multi-hop chains need every
        # hop at exactly the same year. Pre-index (subject, year) → triples
        # so the 2-hop and 3+-hop samplers can forward-chain in O(bucket_size)
        # instead of O(entity_degree across all years).
        self._subject_year: Dict[str, Dict[float, List[Triple]]] = defaultdict(
            lambda: defaultdict(list)
        )
        for t in self.triples:
            self._subject_year[t.subject][t.t_start].append(t)
        self._subjects_with_outgoing: List[str] = list(self._subject_year.keys())

    # --- Public entry point ---------------------------------------------

    def generate_candidates(
        self,
        target_candidates: int = 40000,
        min_depth: int = 1,
        max_depth: int = 4,
    ) -> List[Candidate]:
        """
        Generate candidates across the 12-cell matrix (3 complexity levels ×
        4 temporal operator types). Target per cell is an even split of the
        per-complexity budget (4K/4K/2K per the TempBench paper).

        Implementation: sample chains per complexity, and for each chain try
        each of the four operator builders. PIT and INT succeed for almost
        every chain; BA requires a sibling fact and SEQ requires an earlier
        reference triple, so those buckets yield less per chain.
        """
        # The TempBench paper commits to 4000 / 4000 / 2000 at target_n = 10000.
        # Scale proportionally to target_candidates (= 4 × target_n from the
        # BenchmarkBuilder).
        per_complexity = {
            "1hop": target_candidates // 10,    # 40% of target_n
            "2hop": target_candidates // 10,    # 40% of target_n
            "3plus": target_candidates // 20,   # 20% of target_n
        }
        # 3× oversample to absorb Stage 3/4 attrition (uniqueness + dedup).
        pool_per_complexity = {k: v * 3 for k, v in per_complexity.items()}
        operators = ["point_in_time", "before_after", "interval", "sequence"]

        candidates: List[Candidate] = []
        for complexity, pool_target in pool_per_complexity.items():
            sampler = {
                "1hop": lambda n: self._sample_1hop_chains(n),
                "2hop": lambda n: self._sample_2hop_chains(n),
                "3plus": lambda n: self._sample_3plus_chains(n, max_depth),
            }[complexity]
            # Each chain can produce up to len(operators) candidates, so we
            # only need pool_target / len(operators) chains — but many
            # BA/SEQ attempts fail, so keep a healthy buffer.
            chains = sampler(pool_target // 2)
            for chain, t_query in chains:
                for op in operators:
                    cand = self._build_operator_candidate(
                        op, chain, t_query, complexity
                    )
                    if cand is not None:
                        candidates.append(cand)

        self.rng.shuffle(candidates)
        return candidates

    # --- Chain samplers (return chain + t_query, no templating) ---------

    def _sample_1hop_chains(
        self, target_count: int
    ) -> List[Tuple[List[Triple], float]]:
        chains = []
        sampled = self.rng.sample(
            self.triples, min(len(self.triples), target_count)
        )
        for t in sampled:
            chains.append(([t], t.t_start))
        return chains

    def _sample_2hop_chains(
        self, target_count: int
    ) -> List[Tuple[List[Triple], float]]:
        """
        Year-first 2-hop sampler. Pick an anchor subject that has outgoing
        facts, pick a year from that subject, then find a second hop from the
        pivot at the same year. Much higher success rate than sampling t1
        first and hoping for a matching t2.
        """
        chains = []
        attempts = 0
        max_attempts = target_count * 8
        while len(chains) < target_count and attempts < max_attempts:
            attempts += 1
            anchor = self.rng.choice(self._subjects_with_outgoing)
            year_index = self._subject_year[anchor]
            year = self.rng.choice(list(year_index.keys()))
            t1_candidates = year_index[year]
            t1 = self.rng.choice(t1_candidates)

            pivot_year_index = self._subject_year.get(t1.obj)
            if pivot_year_index is None:
                continue
            t2_candidates = [
                t for t in pivot_year_index.get(year, [])
                if t.relation != t1.relation
                and t.obj != t1.subject  # cycle guard
            ]
            if not t2_candidates:
                continue
            t2 = self.rng.choice(t2_candidates)

            chains.append(([t1, t2], year))
        return chains

    def _sample_3plus_chains(
        self, target_count: int, max_depth: int
    ) -> List[Tuple[List[Triple], float]]:
        """
        Year-first 3+-hop sampler. Pick an anchor subject, pick a year that
        subject has outgoing facts, walk forward through hops at that year.
        Uses the pre-built (subject, year) index for fast forward-chaining.
        """
        chains = []
        attempts = 0
        max_attempts = target_count * 15
        while len(chains) < target_count and attempts < max_attempts:
            attempts += 1
            anchor = self.rng.choice(self._subjects_with_outgoing)
            year_index = self._subject_year[anchor]
            year = self.rng.choice(list(year_index.keys()))
            depth = self.rng.randint(3, min(max_depth, 4))

            chain: List[Triple] = []
            current = anchor
            visited = {current}
            for _ in range(depth):
                hops = [
                    t for t in self._subject_year.get(current, {}).get(year, [])
                    if t.obj not in visited
                ]
                if not hops:
                    break
                hop = self.rng.choice(hops)
                chain.append(hop)
                current = hop.obj
                visited.add(current)

            if len(chain) < 3:
                continue

            if any(
                chain[i].relation == chain[i - 1].relation
                for i in range(1, len(chain))
            ):
                continue

            window = ValidityWindow.full()
            valid = True
            for triple in chain:
                window = TemporalKGIndexer.compose(window, triple, year)
                if window is None or window.is_empty():
                    valid = False
                    break
            if not valid:
                continue

            chains.append((chain, year))
        return chains

    # --- Operator builders ----------------------------------------------

    def _build_operator_candidate(
        self,
        operator: str,
        chain: List[Triple],
        t_query: float,
        complexity: str,
    ) -> Optional[Candidate]:
        """Dispatch to the right operator builder."""
        dispatch = {
            "point_in_time": self._build_pit,
            "before_after": self._build_ba,
            "interval": self._build_interval,
            "sequence": self._build_sequence,
        }
        return dispatch[operator](chain, t_query, complexity)

    def _build_pit(
        self, chain: List[Triple], t_query: float, complexity: str
    ) -> Optional[Candidate]:
        """Point-in-time: "In {year}, what was {path}'s {r_n}?"."""
        path = _render_composition_path(
            chain[0].subject, [h.relation for h in chain[:-1]]
        )
        template = self.rng.choice(QUESTION_TEMPLATES["point_in_time"])
        question = template.format(
            path=path,
            final_relation=chain[-1].relation,
            year=int(t_query),
        )
        return self._make_candidate(
            question, t_query, chain[-1].obj, chain, complexity,
            "point_in_time", "explicit",
        )

    def _build_ba(
        self, chain: List[Triple], t_query: float, complexity: str
    ) -> Optional[Candidate]:
        """
        Before/after: same chain as PIT, but the temporal anchor is a sibling
        fact (another holder of the terminal relation at a different time).
        The candidate is dropped if no such sibling exists.
        """
        terminal = chain[-1]
        siblings = [
            t for t in self.indexer.entity_index.get(terminal.subject, [])
            if t.subject == terminal.subject
            and t.relation == terminal.relation
            and t.obj != terminal.obj
            and t.t_start != t_query
        ]
        if not siblings:
            return None
        sibling = self.rng.choice(siblings)
        # Qualifier: answer came *before* sibling if t_query < sibling.t_start.
        if sibling.t_start > t_query:
            qualifier, qualifier_cap = "before", "Before"
        else:
            qualifier, qualifier_cap = "after", "After"

        path = _render_composition_path(
            chain[0].subject, [h.relation for h in chain[:-1]]
        )
        template = self.rng.choice(QUESTION_TEMPLATES["before_after"])
        question = template.format(
            path=path,
            final_relation=terminal.relation,
            qualifier=qualifier,
            qualifier_cap=qualifier_cap,
            sibling=sibling.obj,
        )
        return self._make_candidate(
            question, t_query, terminal.obj, chain, complexity,
            "before_after", "ordinal",
        )

    def _build_interval(
        self, chain: List[Triple], t_query: float, complexity: str
    ) -> Optional[Candidate]:
        """
        Interval (temporal pinpoint): "In what year was {path}'s {r_n} equal
        to {terminal}?". Answer is the query year. Uniqueness of the year
        is enforced by a custom check in Stage 3 (AnswerUniquenessFilter).
        """
        path = _render_composition_path(
            chain[0].subject, [h.relation for h in chain[:-1]]
        )
        terminal = chain[-1]
        template = self.rng.choice(QUESTION_TEMPLATES["interval"])
        question = template.format(
            path=path,
            final_relation=terminal.relation,
            terminal=terminal.obj,
        )
        return self._make_candidate(
            question, t_query, str(int(t_query)), chain, complexity,
            "interval", "ordinal",
        )

    def _build_sequence(
        self, chain: List[Triple], t_query: float, complexity: str
    ) -> Optional[Candidate]:
        """
        Sequence: "After {ref_subject} {ref_rel} {ref_obj}, what was {path}'s
        {r_n}?". Reference triple is an earlier fact involving any entity in
        the chain (makes the anchor event contextually relevant).
        """
        chain_entities = {h.subject for h in chain} | {h.obj for h in chain}
        chain_ids = {(h.subject, h.relation, h.obj) for h in chain}
        answer_entity = chain[-1].obj
        refs = []
        for e in chain_entities:
            for t in self.indexer.entity_index.get(e, []):
                if (
                    t.t_start < t_query
                    and (t.subject, t.relation, t.obj) not in chain_ids
                    # The reference must not contain the answer anywhere —
                    # otherwise the question literally names its own answer.
                    and t.subject != answer_entity
                    and t.obj != answer_entity
                ):
                    refs.append(t)
        if not refs:
            return None
        ref = self.rng.choice(refs)
        path = _render_composition_path(
            chain[0].subject, [h.relation for h in chain[:-1]]
        )
        template = self.rng.choice(QUESTION_TEMPLATES["sequence"])
        question = template.format(
            path=path,
            final_relation=chain[-1].relation,
            ref_subject=ref.subject,
            ref_relation=ref.relation,
            ref_object=ref.obj,
        )
        return self._make_candidate(
            question, t_query, chain[-1].obj, chain, complexity,
            "sequence", "ordinal",
        )

    def _make_candidate(
        self,
        question: str,
        t_query: float,
        answer: str,
        chain: List[Triple],
        complexity: str,
        operator_type: str,
        question_type: str,
    ) -> Candidate:
        cand = Candidate(
            id=f"cand_{self.candidate_id_counter}",
            question=question,
            t_query=t_query,
            answer=answer,
            complexity=complexity,
            operator_type=operator_type,
            question_type=question_type,
            gold_chain=chain,
        )
        self.candidate_id_counter += 1
        return cand


# ---------------------------------------------------------------------------
# Stage 2: Composability filter
# ---------------------------------------------------------------------------

class ComposabilityFilter:
    """Validates temporal consistency of candidate chains."""

    @staticmethod
    def filter_candidates(candidates: List[Candidate]) -> List[Candidate]:
        """
        Discard candidates whose gold chain has empty composed validity window.
        Uses the ⊕ operator from ValidityWindow.intersect().
        """
        valid = []

        for cand in candidates:
            # Compose all triples in the chain
            window = ValidityWindow.full()
            is_valid = True

            for triple in cand.gold_chain:
                window = TemporalKGIndexer.compose(window, triple, cand.t_query)
                if window is None or window.is_empty():
                    is_valid = False
                    break

            if is_valid:
                valid.append(cand)

        return valid


# ---------------------------------------------------------------------------
# Stage 3: Answer uniqueness filter
# ---------------------------------------------------------------------------

class AnswerUniquenessFilter:
    """Discards ambiguous questions with multiple valid answers at t_query."""

    def __init__(self, indexer: TemporalKGIndexer):
        self.indexer = indexer

    def filter_candidates(self, candidates: List[Candidate]) -> List[Candidate]:
        valid = [c for c in candidates if self._answer_is_unique(c)]
        return valid

    def _answer_is_unique(self, cand: Candidate) -> bool:
        """
        Construction pipeline, Step 4: "removing ambiguous questions with multiple valid
        answers at t_q". Scope is terminal-answer only — intermediate fan-out
        along the chain is permitted.

        Entity-valued operators (PIT, BA, SEQ): the final hop's (subject,
        relation) must have exactly one valid object at t_q, and that object
        must equal the recorded answer.

        Year-valued operator (INT): the specific terminal triple (subject,
        relation, object) must be valid at exactly one distinct t in the KG.
        Otherwise the year-answer is ambiguous.

        See benchmark-design-decisions.md §3 for the full rationale.
        """
        if not cand.gold_chain:
            return False

        terminal = cand.gold_chain[-1]

        if cand.operator_type == "interval":
            # Year answer: the specific (s, r, o) triple must be unique in time.
            matches = [
                t for t in self.indexer.entity_index.get(terminal.subject, [])
                if t.subject == terminal.subject
                and t.relation == terminal.relation
                and t.obj == terminal.obj
            ]
            distinct_years = {t.t_start for t in matches}
            return len(distinct_years) == 1

        # Entity-valued operators: terminal (s, r) must have a single valid
        # object at t_q.
        terminal_objs = {
            t.obj
            for t in self.indexer.entity_index.get(terminal.subject, [])
            if t.subject == terminal.subject
            and t.relation == terminal.relation
            and t.valid_at(cand.t_query)
        }
        return len(terminal_objs) == 1 and cand.answer in terminal_objs


# ---------------------------------------------------------------------------
# Stage 4: MinHash deduplication
# ---------------------------------------------------------------------------

class MinHasher:
    """
    MinHash with Jaccard similarity for deduplicating near-duplicate questions.
    Uses character 3-grams and 128 hash functions.
    """

    def __init__(self, num_hashes: int = 128, gram_size: int = 3, seed: int = 42):
        self.num_hashes = num_hashes
        self.gram_size = gram_size
        self.seed = seed

    @staticmethod
    def _get_grams(text: str, gram_size: int) -> Set[str]:
        """Extract character n-grams from text."""
        text = text.lower()
        return {text[i : i + gram_size] for i in range(len(text) - gram_size + 1)}

    def _hash_gram(self, gram: str, hash_idx: int) -> int:
        """Compute hash value for a gram and hash function index."""
        seed_str = f"{self.seed}_{hash_idx}_{gram}"
        h = hashlib.sha256(seed_str.encode()).hexdigest()
        return int(h, 16)

    def signature(self, text: str) -> List[int]:
        """Compute MinHash signature for a text."""
        grams = self._get_grams(text, self.gram_size)

        if not grams:
            return [0] * self.num_hashes

        sig = []
        for hash_idx in range(self.num_hashes):
            min_hash = float("inf")
            for gram in grams:
                h = self._hash_gram(gram, hash_idx)
                min_hash = min(min_hash, h)
            sig.append(min_hash)

        return sig

    @staticmethod
    def jaccard_similarity(sig_a: List[int], sig_b: List[int]) -> float:
        """Estimate Jaccard similarity from MinHash signatures."""
        if len(sig_a) == 0 or len(sig_b) == 0:
            return 0.0
        matches = sum(1 for a, b in zip(sig_a, sig_b) if a == b)
        return matches / len(sig_a)


class MinHashDeduplicator:
    """Deduplicates candidates using MinHash with Jaccard threshold."""

    def __init__(self, similarity_threshold: float = 0.8, seed: int = 42):
        self.threshold = similarity_threshold
        self.hasher = MinHasher(num_hashes=128, seed=seed)

    def deduplicate(self, candidates: List[Candidate]) -> List[Candidate]:
        """
        Remove near-duplicate questions (Jaccard > threshold).
        Keep the first occurrence of each group.
        """
        if not candidates:
            return []

        # Compute signatures
        sigs = [(c, self.hasher.signature(c.question)) for c in candidates]

        # Greedy clustering: each candidate either starts a cluster or is merged
        clusters = []
        used = set()

        for i, (cand_i, sig_i) in enumerate(sigs):
            if i in used:
                continue

            cluster = [cand_i]
            used.add(i)

            for j in range(i + 1, len(sigs)):
                if j in used:
                    continue

                cand_j, sig_j = sigs[j]
                sim = self.hasher.jaccard_similarity(sig_i, sig_j)

                if sim > self.threshold:
                    used.add(j)

            clusters.append(cluster[0])  # Keep first of each cluster

        return clusters


# ---------------------------------------------------------------------------
# Stage 5: Subgraph construction
# ---------------------------------------------------------------------------

class SubgraphConstructor:
    """
    Builds three subgraphs for each question:
      - S_star: ground truth chain
      - S_dist: distractor (one wrong hop, same relation, different object)
      - S_stale: stale-fact (one hop replaced by temporally adjacent version)
    """

    def __init__(self, indexer: TemporalKGIndexer, seed: int = 42):
        self.indexer = indexer
        self.rng = random.Random(seed)

    def construct(
        self,
        candidate: Candidate,
    ) -> Tuple[List[Dict], List[Dict], List[Dict]]:
        """
        Build S_star, S_dist, S_stale for a candidate.
        Returns (S_star, S_dist, S_stale) as list of triple dicts.
        """
        # S_star: the gold chain
        S_star = [t.to_dict() for t in candidate.gold_chain]

        # S_dist: replace one hop with a distractor (same relation, different object, valid at t_query)
        S_dist = self._build_distractor(candidate)

        # S_stale: replace one hop with a temporally adjacent version
        S_stale = self._build_stale(candidate)

        return S_star, S_dist, S_stale

    def _build_distractor(self, candidate: Candidate) -> List[Dict]:
        """
        Replace one random hop with a semantically similar but wrong triple.
        Same subject, same relation, different object, valid at t_query.
        """
        if not candidate.gold_chain:
            return [t.to_dict() for t in candidate.gold_chain]

        S_dist = [t.to_dict() for t in candidate.gold_chain]
        hop_to_replace = self.rng.randint(0, len(candidate.gold_chain) - 1)
        replaced_triple = candidate.gold_chain[hop_to_replace]

        # Find alternative triples with same (s, r) but different object AT ANY TIME.
        # We can't require valid_at(t_query) — the answer-uniqueness filter has
        # already guaranteed no such alternatives exist, so that constraint would
        # always return an empty list. Taking any alternative object across time
        # gives a semantically plausible but factually wrong distractor (e.g. a
        # former CEO when the question asks about a later year).
        alternatives = [
            t for t in self.indexer.entity_index.get(replaced_triple.subject, [])
            if (t.subject == replaced_triple.subject and
                t.relation == replaced_triple.relation and
                t.obj != replaced_triple.obj)
        ]

        if alternatives:
            distractor = self.rng.choice(alternatives)
            S_dist[hop_to_replace] = distractor.to_dict()

        return S_dist

    def _build_stale(self, candidate: Candidate) -> List[Dict]:
        """
        Replace one hop with a temporally adjacent version
        (same s, r, o but different validity window that does NOT contain t_query).
        """
        if not candidate.gold_chain:
            return [t.to_dict() for t in candidate.gold_chain]

        S_stale = [t.to_dict() for t in candidate.gold_chain]
        hop_to_replace = self.rng.randint(0, len(candidate.gold_chain) - 1)
        replaced_triple = candidate.gold_chain[hop_to_replace]

        # Find temporally adjacent versions of the same triple
        adjacent = [
            t for t in self.indexer._all_triples
            if (t.subject == replaced_triple.subject and
                t.relation == replaced_triple.relation and
                t.obj == replaced_triple.obj and
                t.t_start != replaced_triple.t_start and
                not t.valid_at(candidate.t_query))
        ]

        if adjacent:
            stale_triple = self.rng.choice(adjacent)
            S_stale[hop_to_replace] = stale_triple.to_dict()

        return S_stale


# ---------------------------------------------------------------------------
# Stage 6: Train/dev/test split
# ---------------------------------------------------------------------------

class DatasetSplitter:
    """Stratified split by complexity level."""

    def __init__(self, seed: int = 42):
        self.rng = random.Random(seed)

    def split(
        self,
        questions: List[BenchmarkQuestion],
        train_frac: float = 0.7,
        dev_frac: float = 0.1,
        test_frac: float = 0.2,
    ) -> List[BenchmarkQuestion]:
        """
        Stratified split by complexity.
        Target: 1-hop: 4K (2.8K train), 2-hop: 4K (2.8K train), 3+-hop: 2K (1.4K train)
        """
        # Group by complexity
        by_complexity: Dict[str, List[BenchmarkQuestion]] = defaultdict(list)
        for q in questions:
            by_complexity[q.complexity].append(q)

        # Split each group
        result = []
        for complexity, qs in by_complexity.items():
            self.rng.shuffle(qs)

            n = len(qs)
            train_end = int(n * train_frac)
            dev_end = train_end + int(n * dev_frac)

            for i, q in enumerate(qs):
                if i < train_end:
                    q.split = "train"
                elif i < dev_end:
                    q.split = "dev"
                else:
                    q.split = "test"

            result.extend(qs)

        return result


# ---------------------------------------------------------------------------
# Main builder
# ---------------------------------------------------------------------------

class BenchmarkBuilder:
    """Orchestrates all six pipeline stages."""

    def __init__(
        self,
        kg_path: str,
        output_dir: str = "./benchmark/",
        target_n: int = 10000,
        seed: int = 42,
        min_depth: int = 1,
        max_depth: int = 4,
    ):
        self.kg_path = kg_path
        self.output_dir = Path(output_dir)
        self.target_n = target_n
        self.seed = seed
        self.min_depth = min_depth
        self.max_depth = max_depth
        self.rng = random.Random(seed)

        # Build or load indexer
        self.indexer = TemporalKGIndexer()
        if kg_path.endswith(".json"):
            self.indexer.load_from_json(kg_path)
        else:
            self.indexer.load_tkgl_smallpedia(kg_path)

    def build(self) -> List[BenchmarkQuestion]:
        """Run the full 6-stage pipeline."""
        print("[Benchmark Builder] Starting pipeline...")
        print(f"[Indexer] {self.indexer}")

        # Stage 1: Generate candidates
        print("\n[Stage 1] Question generation...")
        gen = QuestionGenerator(self.indexer, seed=self.seed)
        target_candidates = int(self.target_n * 4)  # 40K to yield 10K
        candidates = gen.generate_candidates(
            target_candidates=target_candidates,
            min_depth=self.min_depth,
            max_depth=self.max_depth,
        )
        print(f"  Generated {len(candidates):,} candidates")

        # Stage 2: Composability filter
        print("\n[Stage 2] Composability filtering...")
        comp_filter = ComposabilityFilter()
        candidates = comp_filter.filter_candidates(candidates)
        print(f"  Passed composability check: {len(candidates):,}")

        # Stage 3: Answer uniqueness filter
        print("\n[Stage 3] Answer uniqueness filtering...")
        uniq_filter = AnswerUniquenessFilter(self.indexer)
        candidates = uniq_filter.filter_candidates(candidates)
        print(f"  Passed uniqueness check: {len(candidates):,}")

        # Stage 4: MinHash deduplication
        print("\n[Stage 4] MinHash deduplication...")
        deduplicator = MinHashDeduplicator(similarity_threshold=0.8, seed=self.seed)
        candidates = deduplicator.deduplicate(candidates)
        print(f"  After deduplication: {len(candidates):,}")

        # Stratified trim: hit the paper's per-complexity targets
        # (4K / 4K / 2K at target_n = 10K) and, within each complexity, spread
        # across the four operator types. Under-yield in an operator cell
        # is topped up with point-in-time from the same complexity, because
        # PIT is the most reliable operator and degrades the benchmark least
        # if it fills in for a short cell.
        candidates = self._stratified_trim(candidates)
        print(f"  Trimmed to target: {len(candidates):,}")

        # Stage 5: Subgraph construction
        print("\n[Stage 5] Subgraph construction...")
        sg_constructor = SubgraphConstructor(self.indexer, seed=self.seed)
        questions = []

        for i, cand in enumerate(candidates):
            S_star, S_dist, S_stale = sg_constructor.construct(cand)

            q = BenchmarkQuestion(
                id=f"q_{i:06d}",
                question=cand.question,
                t_query=cand.t_query,
                answer=cand.answer,
                complexity=cand.complexity,
                operator_type=cand.operator_type,
                question_type=cand.question_type,
                S_star=S_star,
                S_dist=S_dist,
                S_stale=S_stale,
                split="",  # Will be set in Stage 6
            )
            questions.append(q)

        print(f"  Subgraphs constructed: {len(questions):,}")

        # Stage 6: Train/dev/test split
        print("\n[Stage 6] Train/dev/test split (stratified)...")
        splitter = DatasetSplitter(seed=self.seed)
        questions = splitter.split(questions)

        # Print split statistics
        splits = defaultdict(lambda: defaultdict(int))
        for q in questions:
            splits[q.complexity][q.split] += 1

        print("  Split distribution:")
        for complexity in ["1hop", "2hop", "3plus"]:
            if complexity in splits:
                train = splits[complexity]["train"]
                dev = splits[complexity]["dev"]
                test = splits[complexity]["test"]
                total = train + dev + test
                print(f"    {complexity:8s}: {total:5d} ({train:4d} train, {dev:3d} dev, {test:3d} test)")

        return questions

    def _stratified_trim(self, candidates: List[Candidate]) -> List[Candidate]:
        """
        Reduce candidates to per-complexity/per-operator quotas matching paper
        the TempBench paper (4K 1-hop, 4K 2-hop, 2K 3+-hop at target_n = 10K), with each
        complexity split evenly across four operators. Cells that under-yield
        are topped up from PIT in the same complexity.
        """
        per_complexity_target = {
            "1hop":  self.target_n * 4 // 10,   # 40%
            "2hop":  self.target_n * 4 // 10,   # 40%
            "3plus": self.target_n * 2 // 10,   # 20%
        }
        operators = ("point_in_time", "before_after", "interval", "sequence")

        # Bucket candidates by (complexity, operator)
        buckets: Dict[Tuple[str, str], List[Candidate]] = defaultdict(list)
        for c in candidates:
            buckets[(c.complexity, c.operator_type)].append(c)
        for bucket in buckets.values():
            self.rng.shuffle(bucket)

        trimmed: List[Candidate] = []
        for complexity, cx_target in per_complexity_target.items():
            per_op_target = cx_target // len(operators)
            cx_kept: List[Candidate] = []
            # First pass: take up to per_op_target from each operator cell.
            for op in operators:
                cell = buckets.get((complexity, op), [])
                cx_kept.extend(cell[:per_op_target])
            # Top up shortfall with PIT first, then anything available.
            shortfall = cx_target - len(cx_kept)
            if shortfall > 0:
                topup_pool: List[Candidate] = []
                for op in ("point_in_time", "sequence", "before_after", "interval"):
                    cell = buckets.get((complexity, op), [])
                    if len(cell) > per_op_target:
                        topup_pool.extend(cell[per_op_target:])
                self.rng.shuffle(topup_pool)
                cx_kept.extend(topup_pool[:shortfall])
            trimmed.extend(cx_kept)

        self.rng.shuffle(trimmed)
        return trimmed

    def save(self, questions: List[BenchmarkQuestion]) -> None:
        """Write benchmark to JSONL file."""
        self.output_dir.mkdir(parents=True, exist_ok=True)
        output_path = self.output_dir / "benchmark.jsonl"

        with open(output_path, "w", encoding="utf-8") as f:
            for q in questions:
                f.write(json.dumps(q.to_jsonl_dict()) + "\n")

        print(f"\n[Output] Benchmark saved to {output_path}")
        print(f"  {len(questions):,} questions written")


# ---------------------------------------------------------------------------
# Smoke test
# ---------------------------------------------------------------------------

def smoke_test():
    """Run on synthetic Deutsche Bank KG (same 5 triples as indexer.py tests)."""
    print("=" * 70)
    print("SMOKE TEST: TempBench Builder")
    print("=" * 70)

    # Create a temporary indexer with synthetic data
    indexer = TemporalKGIndexer()
    indexer.build([
        ("Deutsche_Bank", "has_CFO", "John_Cryan", 2015.0, 2018.0),
        ("Deutsche_Bank", "has_CFO", "Christian_Sewing", 2018.0, math.inf),
        ("Deutsche_Bank", "settled", "LIBOR_Case", 2015.25, 2015.25),
        ("John_Cryan", "member_of", "Deutsche_Bank", 2015.0, 2018.0),
        ("Christian_Sewing", "member_of", "Deutsche_Bank", 2018.0, math.inf),
    ])

    print(f"\nIndexer: {indexer}\n")

    # Generate candidates
    gen = QuestionGenerator(indexer, seed=42)
    candidates = gen.generate_candidates(
        target_candidates=100,
        min_depth=1,
        max_depth=3,
    )
    print(f"Generated {len(candidates)} candidates")

    # Filter by composability
    comp_filter = ComposabilityFilter()
    candidates = comp_filter.filter_candidates(candidates)
    print(f"Passed composability: {len(candidates)}")

    # Filter by uniqueness
    uniq_filter = AnswerUniquenessFilter(indexer)
    candidates = uniq_filter.filter_candidates(candidates)
    print(f"Passed uniqueness: {len(candidates)}")

    # Deduplicate
    deduplicator = MinHashDeduplicator(similarity_threshold=0.8, seed=42)
    candidates = deduplicator.deduplicate(candidates)
    print(f"After deduplication: {len(candidates)}")

    # Build subgraphs
    sg_constructor = SubgraphConstructor(indexer, seed=42)
    questions = []

    for i, cand in enumerate(candidates[:min(5, len(candidates))]):
        S_star, S_dist, S_stale = sg_constructor.construct(cand)

        q = BenchmarkQuestion(
            id=f"q_{i:06d}",
            question=cand.question,
            t_query=cand.t_query,
            answer=cand.answer,
            complexity=cand.complexity,
            operator_type=cand.operator_type,
            question_type=cand.question_type,
            S_star=S_star,
            S_dist=S_dist,
            S_stale=S_stale,
            split="train",
        )
        questions.append(q)

    print(f"Built {len(questions)} benchmark questions\n")

    # Print sample
    print("Sample questions:")
    for q in questions[:3]:
        print(f"\n  ID: {q.id}")
        print(f"  Question: {q.question}")
        print(f"  Complexity: {q.complexity}")
        print(f"  Answer: {q.answer}")
        print(f"  t_query: {q.t_query}")
        print(f"  Operator: {q.operator_type}")
        print(f"  S_star: {len(q.S_star)} triples")
        print(f"  S_dist: {len(q.S_dist)} triples")
        print(f"  S_stale: {len(q.S_stale)} triples")

    print("\n" + "=" * 70)
    print("SMOKE TEST PASSED")
    print("=" * 70)


# ---------------------------------------------------------------------------
# CLI
# ---------------------------------------------------------------------------

def main():
    parser = argparse.ArgumentParser(
        description="Build TempBench: 10K-question temporal QA benchmark"
    )
    parser.add_argument(
        "--kg_path",
        type=str,
        default=None,
        help="Path to KG file (JSON or TKGL CSV)",
    )
    parser.add_argument(
        "--output_dir",
        type=str,
        default="./benchmark/",
        help="Output directory for benchmark JSONL",
    )
    parser.add_argument(
        "--target_n",
        type=int,
        default=10000,
        help="Target number of benchmark questions (default 10000)",
    )
    parser.add_argument(
        "--seed",
        type=int,
        default=42,
        help="Random seed (default 42)",
    )
    parser.add_argument(
        "--min_depth",
        type=int,
        default=1,
        help="Minimum chain depth (default 1)",
    )
    parser.add_argument(
        "--max_depth",
        type=int,
        default=4,
        help="Maximum chain depth (default 4)",
    )
    parser.add_argument(
        "--smoke_test",
        action="store_true",
        help="Run smoke test on synthetic data",
    )

    args = parser.parse_args()

    if args.smoke_test:
        smoke_test()
        sys.exit(0)

    if not args.kg_path:
        print("Error: --kg_path required (or use --smoke_test)")
        sys.exit(1)

    builder = BenchmarkBuilder(
        kg_path=args.kg_path,
        output_dir=args.output_dir,
        target_n=args.target_n,
        seed=args.seed,
        min_depth=args.min_depth,
        max_depth=args.max_depth,
    )

    questions = builder.build()
    builder.save(questions)


if __name__ == "__main__":
    main()