File size: 29,673 Bytes
6a7089a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
package semantic

// benchmark_study_test.go β€” Controlled benchmark study
//
//   20 queries Γ— 10 page types comparing:
//     β€’ LexicalMatcher (Jaccard + stopwords + role boost)
//     β€’ EmbeddingMatcher (128-dim HashingEmbedder + cosine similarity)
//     β€’ CombinedMatcher (0.6 lexical + 0.4 embedding)
//
//   Metrics reported:
//     β€’ Acc@1 β€” correct element is the top-ranked result
//     β€’ Acc@3 β€” correct element appears in top-3 results
//     β€’ Mean Latency (Β΅s) per matcher
//
//   Run:
//     go test ./internal/semantic/ -run TestBenchmarkStudy -v
//
//   Or with benchmark timing detail:
//     go test ./internal/semantic/ -run TestBenchmarkStudy -v -count 5

import (
	"context"
	"fmt"
	"sort"
	"strings"
	"testing"
	"time"
)

// -----------------------------------------------------------------------
// Data structures
// -----------------------------------------------------------------------

// studyCase is a single (page, query, expected-ref) triple.
type studyCase struct {
	page        string // human-readable page name
	query       string // natural language query
	expectedRef string // ref of the ground-truth element
	elements    []ElementDescriptor
}

// studyResult records one matcher's answer for one case.
type studyResult struct {
	matcherName string
	caseName    string
	page        string
	hit1        bool // Acc@1: best ref == expected
	hit3        bool // Acc@3: expected ref in top-3
	latencyNs   int64
	bestRef     string
	bestScore   float64
}

// -----------------------------------------------------------------------
// Ground-truth page element sets (10 pages Γ— 2 queries each = 20 cases)
// -----------------------------------------------------------------------

func studyCases() []studyCase {
	// ---- Page 1: Login Form ------------------------------------------------
	login := []ElementDescriptor{
		{Ref: "e0", Role: "heading", Name: "Sign In"},
		{Ref: "e1", Role: "textbox", Name: "Email address"},
		{Ref: "e2", Role: "textbox", Name: "Password"},
		{Ref: "e3", Role: "checkbox", Name: "Remember me"},
		{Ref: "e4", Role: "button", Name: "Sign In"},
		{Ref: "e5", Role: "link", Name: "Forgot your password?"},
		{Ref: "e6", Role: "link", Name: "Create account"},
		{Ref: "e7", Role: "button", Name: "Continue with Google"},
		{Ref: "e8", Role: "button", Name: "Continue with Apple"},
		{Ref: "e9", Role: "img", Name: "Company logo"},
	}

	// ---- Page 2: Registration Form -----------------------------------------
	register := []ElementDescriptor{
		{Ref: "e0", Role: "heading", Name: "Create your account"},
		{Ref: "e1", Role: "textbox", Name: "First name"},
		{Ref: "e2", Role: "textbox", Name: "Last name"},
		{Ref: "e3", Role: "textbox", Name: "Email"},
		{Ref: "e4", Role: "textbox", Name: "Password"},
		{Ref: "e5", Role: "textbox", Name: "Confirm password"},
		{Ref: "e6", Role: "combobox", Name: "Date of birth"},
		{Ref: "e7", Role: "combobox", Name: "Country or region"},
		{Ref: "e8", Role: "checkbox", Name: "I agree to the Terms and Conditions"},
		{Ref: "e9", Role: "checkbox", Name: "Subscribe to marketing emails"},
		{Ref: "e10", Role: "button", Name: "Create account"},
		{Ref: "e11", Role: "link", Name: "Already have an account? Log in"},
	}

	// ---- Page 3: E-commerce Product Page -----------------------------------
	product := []ElementDescriptor{
		{Ref: "e0", Role: "heading", Name: "Wireless Noise-Cancelling Headphones"},
		{Ref: "e1", Role: "text", Name: "$299.99"},
		{Ref: "e2", Role: "combobox", Name: "Color", Value: "Midnight Black"},
		{Ref: "e3", Role: "spinbutton", Name: "Quantity", Value: "1"},
		{Ref: "e4", Role: "button", Name: "Add to cart"},
		{Ref: "e5", Role: "button", Name: "Buy now"},
		{Ref: "e6", Role: "button", Name: "Add to wishlist"},
		{Ref: "e7", Role: "tab", Name: "Description"},
		{Ref: "e8", Role: "tab", Name: "Reviews"},
		{Ref: "e9", Role: "tab", Name: "Specifications"},
		{Ref: "e10", Role: "img", Name: "Product image front view"},
		{Ref: "e11", Role: "text", Name: "Free shipping on orders over $50"},
	}

	// ---- Page 4: Navigation Header -----------------------------------------
	nav := []ElementDescriptor{
		{Ref: "e0", Role: "img", Name: "Site logo"},
		{Ref: "e1", Role: "link", Name: "Home"},
		{Ref: "e2", Role: "link", Name: "Products"},
		{Ref: "e3", Role: "link", Name: "Pricing"},
		{Ref: "e4", Role: "link", Name: "Blog"},
		{Ref: "e5", Role: "link", Name: "About Us"},
		{Ref: "e6", Role: "link", Name: "Contact"},
		{Ref: "e7", Role: "search", Name: "Search"},
		{Ref: "e8", Role: "button", Name: "Search"},
		{Ref: "e9", Role: "button", Name: "Open cart"},
		{Ref: "e10", Role: "link", Name: "Sign in"},
		{Ref: "e11", Role: "button", Name: "Open navigation menu"},
	}

	// ---- Page 5: Analytics Dashboard ---------------------------------------
	dashboard := []ElementDescriptor{
		{Ref: "e0", Role: "heading", Name: "Dashboard Overview"},
		{Ref: "e1", Role: "button", Name: "Export Report"},
		{Ref: "e2", Role: "button", Name: "Add Widget"},
		{Ref: "e3", Role: "combobox", Name: "Date range", Value: "Last 30 days"},
		{Ref: "e4", Role: "text", Name: "Total Revenue", Value: "$128,450"},
		{Ref: "e5", Role: "text", Name: "Active Users", Value: "8,302"},
		{Ref: "e6", Role: "text", Name: "Conversion Rate", Value: "3.4%"},
		{Ref: "e7", Role: "text", Name: "Avg Session Duration", Value: "4m 12s"},
		{Ref: "e8", Role: "button", Name: "Refresh Data"},
		{Ref: "e9", Role: "link", Name: "View detailed report"},
		{Ref: "e10", Role: "tab", Name: "Overview"},
		{Ref: "e11", Role: "tab", Name: "Revenue"},
		{Ref: "e12", Role: "tab", Name: "Users"},
		{Ref: "e13", Role: "button", Name: "Notifications"},
	}

	// ---- Page 6: Search Results Page ---------------------------------------
	search := []ElementDescriptor{
		{Ref: "e0", Role: "search", Name: "Search"},
		{Ref: "e1", Role: "button", Name: "Search"},
		{Ref: "e2", Role: "heading", Name: "Search Results for \"golang\""},
		{Ref: "e3", Role: "combobox", Name: "Sort by", Value: "Relevance"},
		{Ref: "e4", Role: "checkbox", Name: "Filter: Last 24 hours"},
		{Ref: "e5", Role: "checkbox", Name: "Filter: Images"},
		{Ref: "e6", Role: "checkbox", Name: "Filter: Videos"},
		{Ref: "e7", Role: "link", Name: "Next page"},
		{Ref: "e8", Role: "link", Name: "Previous page"},
		{Ref: "e9", Role: "button", Name: "Clear filters"},
		{Ref: "e10", Role: "text", Name: "About 4,230,000 results"},
	}

	// ---- Page 7: Admin Data Table ------------------------------------------
	table := []ElementDescriptor{
		{Ref: "e0", Role: "heading", Name: "Order Management"},
		{Ref: "e1", Role: "search", Name: "Search orders"},
		{Ref: "e2", Role: "button", Name: "Create order"},
		{Ref: "e3", Role: "button", Name: "Export to CSV"},
		{Ref: "e4", Role: "combobox", Name: "Status filter", Value: "All"},
		{Ref: "e5", Role: "combobox", Name: "Rows per page", Value: "25"},
		{Ref: "e6", Role: "columnheader", Name: "Order ID"},
		{Ref: "e7", Role: "columnheader", Name: "Customer"},
		{Ref: "e8", Role: "columnheader", Name: "Total"},
		{Ref: "e9", Role: "columnheader", Name: "Status"},
		{Ref: "e10", Role: "button", Name: "Previous page"},
		{Ref: "e11", Role: "button", Name: "Next page"},
		{Ref: "e12", Role: "button", Name: "Bulk delete"},
		{Ref: "e13", Role: "checkbox", Name: "Select all orders"},
	}

	// ---- Page 8: Confirmation Modal ----------------------------------------
	modal := []ElementDescriptor{
		{Ref: "e0", Role: "heading", Name: "Dashboard"},
		{Ref: "e1", Role: "button", Name: "New Project"},
		{Ref: "e2", Role: "dialog", Name: "Delete Project"},
		{Ref: "e3", Role: "heading", Name: "Delete Project"},
		{Ref: "e4", Role: "text", Name: "This will permanently delete the project and all its data. This action cannot be undone."},
		{Ref: "e5", Role: "textbox", Name: "Type project name to confirm"},
		{Ref: "e6", Role: "button", Name: "Delete project"},
		{Ref: "e7", Role: "button", Name: "Cancel"},
		{Ref: "e8", Role: "button", Name: "Close"},
		{Ref: "e9", Role: "navigation", Name: "Sidebar"},
	}

	// ---- Page 9: Settings / Preferences Page --------------------------------
	settings := []ElementDescriptor{
		{Ref: "e0", Role: "heading", Name: "Account Settings"},
		{Ref: "e1", Role: "textbox", Name: "Display name"},
		{Ref: "e2", Role: "textbox", Name: "Email address"},
		{Ref: "e3", Role: "textbox", Name: "Phone number"},
		{Ref: "e4", Role: "combobox", Name: "Language", Value: "English"},
		{Ref: "e5", Role: "combobox", Name: "Timezone", Value: "UTC-5"},
		{Ref: "e6", Role: "switch", Name: "Email notifications"},
		{Ref: "e7", Role: "switch", Name: "Push notifications"},
		{Ref: "e8", Role: "switch", Name: "Dark mode"},
		{Ref: "e9", Role: "button", Name: "Save changes"},
		{Ref: "e10", Role: "button", Name: "Cancel"},
		{Ref: "e11", Role: "button", Name: "Delete account"},
		{Ref: "e12", Role: "link", Name: "Change password"},
	}

	// ---- Page 10: Checkout / Payment Page ----------------------------------
	checkout := []ElementDescriptor{
		{Ref: "e0", Role: "heading", Name: "Checkout"},
		{Ref: "e1", Role: "textbox", Name: "Full name"},
		{Ref: "e2", Role: "textbox", Name: "Email"},
		{Ref: "e3", Role: "textbox", Name: "Shipping address"},
		{Ref: "e4", Role: "textbox", Name: "City"},
		{Ref: "e5", Role: "textbox", Name: "Postal code"},
		{Ref: "e6", Role: "combobox", Name: "Country"},
		{Ref: "e7", Role: "textbox", Name: "Card number"},
		{Ref: "e8", Role: "textbox", Name: "Expiry date"},
		{Ref: "e9", Role: "textbox", Name: "CVV"},
		{Ref: "e10", Role: "checkbox", Name: "Save card for future use"},
		{Ref: "e11", Role: "button", Name: "Place order"},
		{Ref: "e12", Role: "button", Name: "Back to cart"},
		{Ref: "e13", Role: "link", Name: "Apply coupon code"},
	}

	return []studyCase{
		// Page 1: Login β€” 2 queries
		{"Login Form", "sign in button", "e4", login},
		{"Login Form", "email input field", "e1", login},

		// Page 2: Registration β€” 2 queries
		{"Registration Form", "create account button", "e10", register},
		{"Registration Form", "confirm password field", "e5", register},

		// Page 3: E-commerce Product β€” 2 queries
		{"Product Page", "add to cart", "e4", product},
		{"Product Page", "product reviews tab", "e8", product},

		// Page 4: Navigation β€” 2 queries
		{"Navigation Header", "search box", "e7", nav},
		{"Navigation Header", "shopping cart", "e9", nav},

		// Page 5: Dashboard β€” 2 queries
		{"Analytics Dashboard", "export report", "e1", dashboard},
		{"Analytics Dashboard", "date range selector", "e3", dashboard},

		// Page 6: Search Results β€” 2 queries
		{"Search Results", "search input", "e0", search},
		{"Search Results", "next page link", "e7", search},

		// Page 7: Data Table β€” 2 queries
		{"Admin Data Table", "search orders", "e1", table},
		{"Admin Data Table", "export csv", "e3", table},

		// Page 8: Modal β€” 2 queries
		{"Confirmation Modal", "cancel button", "e7", modal},
		{"Confirmation Modal", "confirm deletion input", "e5", modal},

		// Page 9: Settings β€” 2 queries
		{"Settings Page", "save changes button", "e9", settings},
		{"Settings Page", "dark mode toggle", "e8", settings},

		// Page 10: Checkout β€” 2 queries
		{"Checkout Page", "place order button", "e11", checkout},
		{"Checkout Page", "card number field", "e7", checkout},
	}
}

// studyHardCases returns 10 intentionally-challenging query/element pairs
// designed to reveal differentiation between matchers:
//
//	Group A (query uses an abbreviation, 0 lexical word overlap):
//	  expects embedding to win via character n-gram similarity.
//
//	Group B (query uses a paraphrase / synonym):
//	  expects both matchers to struggle, revealing the ceiling of
//	  surface-form-only matching.
//
//	Group C (ambiguous β€” multiple equally-plausible elements):
//	  expects combined to win via score averaging.
func studyHardCases() []studyCase {
	// Reuse page element sets from studyCases.
	cases := studyCases()

	// Helper: find element slice for a given page name.
	pageElems := map[string][]ElementDescriptor{}
	for _, c := range cases {
		if _, ok := pageElems[c.page]; !ok {
			pageElems[c.page] = c.elements
		}
	}

	product := pageElems["Product Page"]
	checkout := pageElems["Checkout Page"]
	login := pageElems["Login Form"]
	register := pageElems["Registration Form"]
	settings := pageElems["Settings Page"]
	table := pageElems["Admin Data Table"]
	modal := pageElems["Confirmation Modal"]

	return []studyCase{
		// ── Group A: Abbreviations (lexical = 0, embedding has n-gram overlap) ──

		// "specs"     ↔ "Specifications" β€” shares "^sp","spe","pec","spec" (4-gram)
		{"Product Page [HARD]", "specs tab", "e9", product},

		// "qty"       ↔ "Quantity" β€” shares "^q","ty","y$"
		{"Product Page [HARD]", "qty input", "e3", product},

		// "addr"      ↔ "address" β€” shares "^a","ad","dd","dr"
		{"Checkout Page [HARD]", "addr field", "e3", checkout},

		// "pwd"       ↔ "Password" β€” shares "^p","d$" (weak but present)
		{"Login Form [HARD]", "pwd textbox", "e2", login},

		// "notifs"    ↔ "notifications" β€” shares "not","oti"
		{"Settings Page [HARD]", "toggle email notifs", "e6", settings},

		// ── Group B: Paraphrases / synonyms (no character overlap, both expected to struggle) ──

		// "download"  ↔ "Export to CSV"  β€” no shared characters
		{"Admin Data Table [HARD]", "download table data", "e3", table},

		// "proceed"   ↔ "Place order"    β€” no shared characters
		{"Checkout Page [HARD]", "proceed to payment", "e11", checkout},

		// "sign up"   ↔ "Create account" β€” no shared characters
		{"Registration Form [HARD]", "sign up now", "e10", register},

		// "dismiss"   ↔ "Cancel"         β€” no shared characters
		{"Confirmation Modal [HARD]", "dismiss dialog", "e7", modal},

		// ── Group C: Ambiguous (multiple "button" elements, exact name helps) ──

		// "dark theme" ↔ "Dark mode" switch β€” "dark" word-matches exactly
		{"Settings Page [HARD]", "dark theme switch", "e8", settings},
	}
}

// -----------------------------------------------------------------------
// Core evaluation logic
// -----------------------------------------------------------------------

func runMatcher(
	name string,
	matcher ElementMatcher,
	cases []studyCase,
) []studyResult {
	ctx := context.Background()
	opts := FindOptions{Threshold: 0.0, TopK: 3}
	results := make([]studyResult, 0, len(cases))

	for _, c := range cases {
		start := time.Now()
		fr, err := matcher.Find(ctx, c.query, c.elements, opts)
		elapsed := time.Since(start).Nanoseconds()

		if err != nil {
			results = append(results, studyResult{
				matcherName: name,
				caseName:    fmt.Sprintf("%s | %q", c.page, c.query),
				page:        c.page,
				latencyNs:   elapsed,
			})
			continue
		}

		// Acc@1
		hit1 := fr.BestRef == c.expectedRef

		// Acc@3 β€” expected ref in any of the top-3 matches
		hit3 := hit1
		if !hit3 {
			for _, m := range fr.Matches {
				if m.Ref == c.expectedRef {
					hit3 = true
					break
				}
			}
		}

		results = append(results, studyResult{
			matcherName: name,
			caseName:    fmt.Sprintf("%s | %q", c.page, c.query),
			page:        c.page,
			hit1:        hit1,
			hit3:        hit3,
			latencyNs:   elapsed,
			bestRef:     fr.BestRef,
			bestScore:   fr.BestScore,
		})
	}

	return results
}

// -----------------------------------------------------------------------
// Report generation helpers
// -----------------------------------------------------------------------

func percent(n, total int) string {
	if total == 0 {
		return " 0.0%"
	}
	return fmt.Sprintf("%5.1f%%", float64(n)/float64(total)*100)
}

func meanLatencyUs(results []studyResult) float64 {
	if len(results) == 0 {
		return 0
	}
	var sum int64
	for _, r := range results {
		sum += r.latencyNs
	}
	return float64(sum) / float64(len(results)) / 1000.0
}

func acc(results []studyResult, k int) (int, int) {
	hits := 0
	for _, r := range results {
		if k == 1 && r.hit1 {
			hits++
		}
		if k == 3 && r.hit3 {
			hits++
		}
	}
	return hits, len(results)
}

func printSeparator(t *testing.T, char string, width int) {
	t.Log(strings.Repeat(char, width))
}

// -----------------------------------------------------------------------
// Main study test
// -----------------------------------------------------------------------

func TestBenchmarkStudy(t *testing.T) {
	cases := studyCases()

	matchers := []struct {
		name    string
		matcher ElementMatcher
	}{
		{"Lexical", NewLexicalMatcher()},
		{"Embedding", NewEmbeddingMatcher(NewHashingEmbedder(128))},
		{"Combined", NewCombinedMatcher(NewHashingEmbedder(128))},
	}

	// Run all matchers
	allResults := make(map[string][]studyResult, len(matchers))
	for _, m := range matchers {
		allResults[m.name] = runMatcher(m.name, m.matcher, cases)
	}

	// ----------------------------------------------------------------
	// REPORT HEADER
	// ----------------------------------------------------------------
	const W = 72
	t.Log("")
	printSeparator(t, "═", W)
	t.Log("  SEMANTIC MATCHING β€” CONTROLLED BENCHMARK STUDY")
	t.Logf("  %d queries Γ— %d page types  |  3 matchers  |  TopK=3  |  Threshold=0",
		len(cases), 10)
	printSeparator(t, "═", W)

	// ----------------------------------------------------------------
	// OVERALL SUMMARY TABLE
	// ----------------------------------------------------------------
	t.Log("")
	t.Log("  OVERALL RESULTS")
	t.Log("")
	t.Logf("  %-12s  %7s  %7s  %12s", "Matcher", "Acc@1", "Acc@3", "Latency (Β΅s)")
	t.Log("  " + strings.Repeat("-", 46))

	type summaryRow struct {
		name    string
		acc1    int
		acc3    int
		total   int
		latency float64
	}
	rows := make([]summaryRow, 0, len(matchers))

	for _, m := range matchers {
		res := allResults[m.name]
		h1, tot := acc(res, 1)
		h3, _ := acc(res, 3)
		lat := meanLatencyUs(res)
		rows = append(rows, summaryRow{m.name, h1, h3, tot, lat})
		t.Logf("  %-12s  %s  %s  %10.1f Β΅s",
			m.name, percent(h1, tot), percent(h3, tot), lat)
	}

	t.Log("  " + strings.Repeat("-", 46))
	t.Log("")

	// ----------------------------------------------------------------
	// PER-PAGE BREAKDOWN
	// ----------------------------------------------------------------
	// Collect unique page names in order
	pages := make([]string, 0, 10)
	seen := map[string]bool{}
	for _, c := range cases {
		if !seen[c.page] {
			pages = append(pages, c.page)
			seen[c.page] = true
		}
	}

	printSeparator(t, "─", W)
	t.Log("  PER-PAGE BREAKDOWN  (Acc@1 / Acc@3)  ")
	printSeparator(t, "─", W)
	t.Log("")
	t.Logf("  %-26s  %-14s  %-14s  %-14s", "Page", "Lexical", "Embedding", "Combined")
	t.Log("  " + strings.Repeat("-", 66))

	for _, page := range pages {
		// Filter results for this page
		cols := make([]string, 0, 3)
		for _, m := range matchers {
			var pageRes []studyResult
			for _, r := range allResults[m.name] {
				if r.page == page {
					pageRes = append(pageRes, r)
				}
			}
			h1, tot := acc(pageRes, 1)
			h3, _ := acc(pageRes, 3)
			cols = append(cols, fmt.Sprintf("%s / %s", percent(h1, tot), percent(h3, tot)))
		}
		t.Logf("  %-26s  %-14s  %-14s  %-14s", page, cols[0], cols[1], cols[2])
	}
	t.Log("")

	// ----------------------------------------------------------------
	// DETAILED CASE-BY-CASE TABLE
	// ----------------------------------------------------------------
	printSeparator(t, "─", W)
	t.Log("  CASE-BY-CASE RESULTS  (βœ“ = hit, βœ— = miss)  ")
	printSeparator(t, "─", W)
	t.Log("")
	t.Logf("  %-6s  %-28s  %-8s  %-8s  %-8s  %-8s  %-8s  %-8s",
		"#", "Query", "Lex@1", "Lex@3", "Emb@1", "Emb@3", "Com@1", "Com@3")
	t.Log("  " + strings.Repeat("-", 88))

	mark := func(hit bool) string {
		if hit {
			return "  βœ“"
		}
		return "  βœ—"
	}

	for i, c := range cases {
		shortQ := c.query
		if len(shortQ) > 27 {
			shortQ = shortQ[:24] + "..."
		}

		lex := allResults["Lexical"][i]
		emb := allResults["Embedding"][i]
		com := allResults["Combined"][i]

		t.Logf("  %3d.   %-28s  %-8s  %-8s  %-8s  %-8s  %-8s  %-8s",
			i+1, shortQ,
			mark(lex.hit1), mark(lex.hit3),
			mark(emb.hit1), mark(emb.hit3),
			mark(com.hit1), mark(com.hit3),
		)
	}
	t.Log("")

	// ----------------------------------------------------------------
	// MISSED CASES ANALYSIS
	// ----------------------------------------------------------------
	printSeparator(t, "─", W)
	t.Log("  MISSED CASES ANALYSIS  (Acc@1 misses)")
	printSeparator(t, "─", W)
	t.Log("")

	for _, m := range matchers {
		missCount := 0
		for _, r := range allResults[m.name] {
			if !r.hit1 {
				missCount++
			}
		}
		if missCount == 0 {
			t.Logf("  %s: perfect score β€” no Acc@1 misses", m.name)
			continue
		}
		t.Logf("  %s misses (%d):", m.name, missCount)
		for i, r := range allResults[m.name] {
			if r.hit1 {
				continue
			}
			t.Logf("    [%2d] %-28s  expected=%-4s  got=%-4s  score=%.3f",
				i+1, fmt.Sprintf("%q", cases[i].query),
				cases[i].expectedRef, r.bestRef, r.bestScore)
		}
	}
	t.Log("")

	// ----------------------------------------------------------------
	// MATCHER COMPARISON: cases where they DISAGREE
	// ----------------------------------------------------------------
	printSeparator(t, "─", W)
	t.Log("  DISAGREMENT ANALYSIS  (where Combined beats both)")
	printSeparator(t, "─", W)
	t.Log("")

	improvements := 0
	for i := range cases {
		lex := allResults["Lexical"][i]
		emb := allResults["Embedding"][i]
		com := allResults["Combined"][i]

		if !lex.hit1 && !emb.hit1 && com.hit1 {
			improvements++
			t.Logf("  [%2d] %q β€” Combined rescued (lexβœ— embβœ— comβœ“)",
				i+1, cases[i].query)
		}
		if lex.hit1 && emb.hit1 && !com.hit1 {
			t.Logf("  [%2d] %q β€” Combined degraded (lexβœ“ embβœ“ comβœ—) !",
				i+1, cases[i].query)
		}
	}
	if improvements == 0 {
		t.Log("  No unique rescues by Combined (or none needed)")
	}
	t.Log("")

	// ----------------------------------------------------------------
	// LATENCY COMPARISON
	// ----------------------------------------------------------------
	printSeparator(t, "─", W)
	t.Log("  LATENCY SUMMARY")
	printSeparator(t, "─", W)
	t.Log("")

	// Sort by latency ascending
	sort.Slice(rows, func(i, j int) bool {
		return rows[i].latency < rows[j].latency
	})

	baseline := rows[0].latency
	for _, row := range rows {
		overhead := ""
		if row.latency > baseline {
			overhead = fmt.Sprintf("  (+%.1fx)", row.latency/baseline)
		}
		t.Logf("  %-12s  %8.2f Β΅s%s", row.name, row.latency, overhead)
	}
	t.Log("")

	// ----------------------------------------------------------------
	// FINAL VERDICT
	// ----------------------------------------------------------------
	printSeparator(t, "═", W)
	t.Log("  VERDICT")
	printSeparator(t, "─", W)
	t.Log("")

	// Find best Acc@1
	bestAcc1Name := ""
	bestAcc1 := -1
	for _, m := range matchers {
		h1, tot := acc(allResults[m.name], 1)
		pct := h1 * 100 / tot
		if pct > bestAcc1 {
			bestAcc1 = pct
			bestAcc1Name = m.name
		}
	}

	lexH1, tot := acc(allResults["Lexical"], 1)
	embH1, _ := acc(allResults["Embedding"], 1)
	comH1, _ := acc(allResults["Combined"], 1)
	lexH3, _ := acc(allResults["Lexical"], 3)
	embH3, _ := acc(allResults["Embedding"], 3)
	comH3, _ := acc(allResults["Combined"], 3)

	t.Logf("  Best Acc@1:  %s (%d/%d = %s)", bestAcc1Name, comH1, tot, percent(comH1, tot))
	t.Log("")
	t.Logf("  Acc@1 β€” Lexical: %s  Embedding: %s  Combined: %s",
		percent(lexH1, tot), percent(embH1, tot), percent(comH1, tot))
	t.Logf("  Acc@3 β€” Lexical: %s  Embedding: %s  Combined: %s",
		percent(lexH3, tot), percent(embH3, tot), percent(comH3, tot))
	t.Log("")
	t.Logf("  Mean latency β€” Lexical: %.1fΒ΅s  Embedding: %.1fΒ΅s  Combined: %.1fΒ΅s",
		meanLatencyUs(allResults["Lexical"]),
		meanLatencyUs(allResults["Embedding"]),
		meanLatencyUs(allResults["Combined"]))
	t.Log("")
	printSeparator(t, "═", W)
	t.Log("")

	// ================================================================
	// PART II β€” HARD CASES (abbreviations, synonyms, paraphrases)
	// ================================================================
	hardCases := studyHardCases()

	allHard := make(map[string][]studyResult, len(matchers))
	for _, m := range matchers {
		allHard[m.name] = runMatcher(m.name, m.matcher, hardCases)
	}

	t.Log("")
	printSeparator(t, "═", W)
	t.Log("  PART II β€” HARD CASES  (abbreviations, synonyms, paraphrases)")
	t.Logf("  %d queries  |  3 matcher groups:  A=abbrev  B=synonym  C=ambiguous",
		len(hardCases))
	printSeparator(t, "═", W)

	// Overall hard summary
	t.Log("")
	t.Log("  HARD OVERALL")
	t.Log("")
	t.Logf("  %-12s  %7s  %7s  %12s", "Matcher", "Acc@1", "Acc@3", "Latency (Β΅s)")
	t.Log("  " + strings.Repeat("-", 46))
	for _, m := range matchers {
		res := allHard[m.name]
		h1, tot := acc(res, 1)
		h3, _ := acc(res, 3)
		lat := meanLatencyUs(res)
		t.Logf("  %-12s  %s  %s  %10.1f Β΅s",
			m.name, percent(h1, tot), percent(h3, tot), lat)
	}
	t.Log("  " + strings.Repeat("-", 46))
	t.Log("")

	// Case-by-case hard results
	printSeparator(t, "─", W)
	t.Log("  HARD CASE-BY-CASE  (βœ“ = hit, βœ— = miss)")
	printSeparator(t, "─", W)
	t.Log("")
	t.Logf("  %-3s  %-3s  %-30s  %-8s  %-8s  %-8s  %-8s  %-8s  %-8s",
		"#", "Grp", "Query", "Lex@1", "Lex@3", "Emb@1", "Emb@3", "Com@1", "Com@3")
	t.Log("  " + strings.Repeat("-", 90))

	groups := []string{"A", "A", "A", "A", "A", "B", "B", "B", "B", "C"}
	for i, c := range hardCases {
		grp := groups[i]
		shortQ := c.query
		if len(shortQ) > 29 {
			shortQ = shortQ[:26] + "..."
		}
		lex := allHard["Lexical"][i]
		emb := allHard["Embedding"][i]
		com := allHard["Combined"][i]

		t.Logf("  %3d  %-3s  %-30s  %-8s  %-8s  %-8s  %-8s  %-8s  %-8s",
			i+1, grp, shortQ,
			mark(lex.hit1), mark(lex.hit3),
			mark(emb.hit1), mark(emb.hit3),
			mark(com.hit1), mark(com.hit3),
		)
	}
	t.Log("")

	// Per-group analysis
	printSeparator(t, "─", W)
	t.Log("  GROUP ANALYSIS")
	printSeparator(t, "─", W)
	t.Log("")
	t.Logf("  %-20s  %-14s  %-14s  %-14s", "Group", "Lexical Acc@1", "Embedding Acc@1", "Combined Acc@1")
	t.Log("  " + strings.Repeat("-", 66))

	groupDefs := []struct {
		label string
		ids   []int // 0-indexed
		desc  string
	}{
		{"A (abbreviations)", []int{0, 1, 2, 3, 4}, "expected: Emb β‰₯ Lex"},
		{"B (synonyms)", []int{5, 6, 7, 8}, "expected: both struggle"},
		{"C (ambiguous)", []int{9}, "expected: Combined wins"},
	}

	for _, gd := range groupDefs {
		for _, mname := range []string{"Lexical", "Embedding", "Combined"} {
			var subset []studyResult
			for _, idx := range gd.ids {
				subset = append(subset, allHard[mname][idx])
			}
			_ = subset
		}
		lexSub := filterByIdx(allHard["Lexical"], gd.ids)
		embSub := filterByIdx(allHard["Embedding"], gd.ids)
		comSub := filterByIdx(allHard["Combined"], gd.ids)
		lh1, lt := acc(lexSub, 1)
		eh1, et := acc(embSub, 1)
		ch1, ct := acc(comSub, 1)
		t.Logf("  %-20s  %-14s  %-15s  %-14s   %s",
			gd.label,
			percent(lh1, lt), percent(eh1, et), percent(ch1, ct),
			gd.desc)
	}
	t.Log("")

	// Combined vs Individual: misses that Combined rescues
	printSeparator(t, "─", W)
	t.Log("  COMBINED RESCUES  (in hard cases)")
	printSeparator(t, "─", W)
	t.Log("")
	rescueCount := 0
	for i := range hardCases {
		lex := allHard["Lexical"][i]
		emb := allHard["Embedding"][i]
		com := allHard["Combined"][i]
		if !lex.hit1 && !emb.hit1 && com.hit1 {
			rescueCount++
			t.Logf("  RESCUE [%d] %q β€” Lexβœ— Embβœ— Comβœ“", i+1, hardCases[i].query)
		}
		if !lex.hit1 && emb.hit1 && com.hit1 {
			t.Logf("  EMB WIN [%d] %q β€” Lexβœ— Embβœ“ Comβœ“", i+1, hardCases[i].query)
		}
		if lex.hit1 && !emb.hit1 && com.hit1 {
			t.Logf("  LEX WIN [%d] %q β€” Lexβœ“ Embβœ— Comβœ“", i+1, hardCases[i].query)
		}
		if lex.hit1 && !emb.hit1 && !com.hit1 {
			t.Logf("  COM FAIL[%d] %q β€” Lexβœ“ Embβœ— Comβœ—  ← embedding dragged score down", i+1, hardCases[i].query)
		}
	}
	if rescueCount == 0 {
		t.Log("  No unique Combined rescues in hard cases")
	}
	t.Log("")

	// Score comparison for hard cases
	printSeparator(t, "─", W)
	t.Log("  SCORE DETAIL  (best score returned by each matcher per hard case)")
	printSeparator(t, "─", W)
	t.Log("")
	t.Logf("  %-3s  %-30s  %-6s  %-8s  %-8s  %-8s  %-8s",
		"#", "Query", "Want", "Lex score", "Emb score", "Com score", "Winner")
	t.Log("  " + strings.Repeat("-", 78))
	for i, c := range hardCases {
		lex := allHard["Lexical"][i]
		emb := allHard["Embedding"][i]
		com := allHard["Combined"][i]
		shortQ := c.query
		if len(shortQ) > 29 {
			shortQ = shortQ[:26] + "..."
		}
		var winner string
		if !lex.hit1 && emb.hit1 {
			winner = "Embedding"
		} else if lex.hit1 && !emb.hit1 {
			winner = "Lexical"
		} else if lex.hit1 && emb.hit1 {
			winner = "both"
		} else {
			winner = "none"
		}
		t.Logf("  %3d  %-30s  %-6s  %9.3f  %9.3f  %9.3f  %s",
			i+1, shortQ, c.expectedRef,
			lex.bestScore, emb.bestScore, com.bestScore, winner)
	}
	t.Log("")

	// Final combined verdict
	printSeparator(t, "═", W)
	t.Log("  FINAL VERDICT β€” EASY + HARD COMBINED")
	printSeparator(t, "─", W)
	t.Log("")

	allTotal := len(cases) + len(hardCases)
	for _, m := range matchers {
		combined := append(allResults[m.name], allHard[m.name]...)
		h1, _ := acc(combined, 1)
		h3, _ := acc(combined, 3)
		lat := meanLatencyUs(combined)
		t.Logf("  %-12s  Acc@1=%s  Acc@3=%s  Β΅s=%.1f  (total %d queries)",
			m.name, percent(h1, allTotal), percent(h3, allTotal), lat, allTotal)
	}
	t.Log("")
	printSeparator(t, "═", W)
	t.Log("")
}

// filterByIdx returns results at specified 0-based indices.
func filterByIdx(results []studyResult, indices []int) []studyResult {
	out := make([]studyResult, 0, len(indices))
	for _, i := range indices {
		if i < len(results) {
			out = append(out, results[i])
		}
	}
	return out
}