blockpedia 0.1.9

A comprehensive Rust library for Minecraft block data with advanced color analysis and palette generation
Documentation
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
#[cfg(test)]
mod milestone1_tests {
    use std::fs;
    use std::path::Path;

    #[test]
    fn can_download_or_load_cached_json() {
        // For milestone 1, check local test file
        assert!(Path::new("test_blocks_data.json").exists());
    }

    #[test]
    fn json_has_expected_structure() {
        let json_data = fs::read_to_string("test_blocks_data.json").unwrap();
        let json: serde_json::Value = serde_json::from_str(&json_data).unwrap();
        assert!(json.is_object());
        assert!(json.get("blocks").is_some());
        assert!(json["blocks"].as_object().unwrap().len() >= 3); // Our test has 3 blocks
    }

    #[test]
    fn sample_blocks_have_required_fields() {
        let json_data = fs::read_to_string("test_blocks_data.json").unwrap();
        let blocks = serde_json::from_str::<serde_json::Value>(&json_data).unwrap();
        let stone = &blocks["blocks"]["minecraft:stone"];
        assert!(stone.get("properties").is_some());
        assert!(stone.get("default_state").is_some());
    }

    #[test]
    fn can_parse_block_properties() {
        let json_data = fs::read_to_string("test_blocks_data.json").unwrap();
        let blocks = serde_json::from_str::<serde_json::Value>(&json_data).unwrap();
        let repeater = &blocks["blocks"]["minecraft:repeater"];
        let props = repeater["properties"].as_object().unwrap();
        assert!(props.contains_key("delay"));
        assert_eq!(props["delay"], serde_json::json!(["1", "2", "3", "4"]));
    }
}

// Milestone 7 Tests: Error Handling & Validation
#[cfg(test)]
mod milestone7_tests {
    use crate::{errors::*, queries::validated::*};

    #[test]
    fn validation_rejects_invalid_block_ids() {
        // Empty block ID
        let result = validation::validate_block_id("");
        assert!(result.is_err());

        // Invalid characters
        let result = validation::validate_block_id("minecraft:invalid!block");
        assert!(result.is_err());

        // Valid block ID should pass
        let result = validation::validate_block_id("minecraft:valid_block");
        assert!(result.is_ok());
    }

    #[test]
    fn validation_rejects_invalid_property_names() {
        // Empty property name
        let result = validation::validate_property_name("");
        assert!(result.is_err());

        // Invalid characters
        let result = validation::validate_property_name("invalid-property!");
        assert!(result.is_err());

        // Valid property name should pass
        let result = validation::validate_property_name("valid_property");
        assert!(result.is_ok());
    }

    #[test]
    fn error_types_display_correctly() {
        let error = BlockpediaError::block_not_found("test:block");
        let error_string = error.to_string();
        assert!(error_string.contains("Block error"));
        assert!(error_string.contains("test:block"));

        let error = BlockpediaError::invalid_property_value(
            "test:block",
            "prop",
            "value",
            vec!["valid1".to_string(), "valid2".to_string()],
        );
        let error_string = error.to_string();
        assert!(error_string.contains("Property error"));
        assert!(error_string.contains("Invalid value"));
    }

    #[test]
    fn safe_query_functions_validate_input() {
        // Test safe property search with invalid property name
        let result = find_blocks_by_property_safe("invalid-prop!", "value");
        assert!(result.is_err());

        // Test safe search with empty pattern
        let result = search_blocks_safe("");
        assert!(result.is_err());

        // Test valid inputs work
        let result = find_blocks_by_property_safe("delay", "1");
        assert!(result.is_ok());
    }

    #[test]
    fn error_recovery_provides_suggestions() {
        let suggestions = recovery::suggest_similar_blocks("stone");
        assert!(!suggestions.is_empty());
        assert!(suggestions.iter().any(|s| s.contains("minecraft:stone")));

        let suggestions = recovery::suggest_property_values(
            "delay",
            "5",
            &[
                "1".to_string(),
                "2".to_string(),
                "3".to_string(),
                "4".to_string(),
            ],
        );
        assert!(!suggestions.is_empty());
    }

    #[test]
    fn comprehensive_validation_catches_multiple_errors() {
        let properties = vec![
            ("delay".to_string(), "5".to_string()), // Invalid value
            ("invalid_prop".to_string(), "value".to_string()), // Invalid property
        ];

        let result = validate_block_properties_safe("minecraft:repeater", &properties);
        assert!(result.is_err());

        if let Err(BlockpediaError::State(StateError::ValidationFailed { errors, .. })) = result {
            assert!(errors.len() >= 2); // Should catch both errors
        } else {
            panic!("Expected ValidationFailed error with multiple errors");
        }
    }

    #[test]
    fn safe_block_state_creation_with_helpful_errors() {
        let properties = vec![
            ("delay".to_string(), "3".to_string()), // Valid
            ("facing".to_string(), "invalid_direction".to_string()), // Invalid value
        ];

        let result = create_block_state_safe("minecraft:repeater", &properties);
        assert!(result.is_err());

        // Error should include suggestions
        let error_msg = result.unwrap_err().to_string();
        assert!(error_msg.contains("Invalid value") || error_msg.contains("ValidationFailed"));
    }

    #[test]
    fn parse_error_recovery_fixes_common_mistakes() {
        let broken_input = "minecraft:repeater delay=3,facing=north";
        let fixed = recovery::fix_common_parse_errors(broken_input);
        // This is a simple example - real implementation would be more sophisticated
        assert_ne!(broken_input, fixed);
    }

    #[test]
    fn structured_errors_are_comparable() {
        let error1 = BlockpediaError::block_not_found("test:block");
        let error2 = BlockpediaError::block_not_found("test:block");
        let error3 = BlockpediaError::block_not_found("other:block");

        assert_eq!(error1, error2);
        assert_ne!(error1, error3);
    }

    #[test]
    fn query_timeout_validation() {
        let result = query_with_timeout("valid_query", || "result");
        assert!(result.is_ok());

        let very_long_name = "a".repeat(100);
        let result = query_with_timeout(&very_long_name, || "result");
        assert!(result.is_err());
    }
}

// Milestone 6 Tests: Fetcher Framework
#[cfg(test)]
mod milestone6_tests {
    use crate::BLOCKS;

    #[test]
    fn fetcher_framework_provides_extra_data() {
        // Test that fetcher framework successfully adds extra data
        let stone = BLOCKS.get("minecraft:stone").unwrap();

        // Stone should have mock data from MockFetcher
        assert_eq!(stone.extras.mock_data, Some(42));

        // Stone should have color data from ColorFetcher
        assert!(stone.extras.color.is_some());
        let color = stone.extras.color.unwrap();
        assert_eq!(color.rgb, [125, 125, 125]);
        assert!((color.oklab[0] - 0.49).abs() < 0.01); // Calculated L value for RGB [125, 125, 125]
    }

    #[test]
    fn fetcher_data_varies_by_block() {
        let stone = BLOCKS.get("minecraft:stone").unwrap();
        let dirt = BLOCKS.get("minecraft:dirt").unwrap();

        // Different blocks should have different mock data
        assert_eq!(stone.extras.mock_data, Some(42));
        assert_eq!(dirt.extras.mock_data, Some(123));

        // Different blocks should have different color data
        let stone_color = stone.extras.color.unwrap();
        let dirt_color = dirt.extras.color.unwrap();
        assert_ne!(stone_color.rgb, dirt_color.rgb);
    }

    #[test]
    fn blocks_without_fetcher_data_have_none() {
        let repeater = BLOCKS.get("minecraft:repeater").unwrap();

        // Repeater was not included in our test fetcher data
        assert_eq!(repeater.extras.mock_data, None);
        assert!(repeater.extras.color.is_none());
    }

    #[test]
    fn generated_color_queries_work() {
        // Test closest color query using stone's actual RGB value
        let closest = crate::BlockFacts::closest_to_color([125, 125, 125]);
        assert!(closest.is_some());

        // Should find a valid block with color data
        let closest_block = closest.unwrap();
        assert!(closest_block.id().contains("minecraft:"));

        // The closest block should have color data
        assert!(closest_block.extras.color.is_some());
    }

    #[test]
    fn color_range_query_works() {
        // Test color range query - the generated function returns a Vec, not an iterator
        let similar_blocks = crate::BlockFacts::blocks_in_color_range([100, 100, 100], 100.0);

        // Should find both stone and dirt in this range
        assert!(!similar_blocks.is_empty());
        let block_ids: Vec<_> = similar_blocks.iter().map(|b| b.id()).collect();
        assert!(block_ids.contains(&"minecraft:stone"));
        assert!(block_ids.contains(&"minecraft:dirt"));
    }

    #[test]
    fn extras_struct_has_proper_defaults() {
        let default_extras = crate::Extras::default();
        assert_eq!(default_extras.mock_data, None);
        assert!(default_extras.color.is_none());

        let new_extras = crate::Extras::new();
        assert_eq!(new_extras.mock_data, None);
        assert!(new_extras.color.is_none());
    }
}

#[cfg(test)]
mod milestone5_tests {
    use crate::queries::*;

    #[test]
    fn enhanced_block_families_logical() {
        let families = get_enhanced_block_families();

        assert!(!families.is_empty());

        // Validate some family groupings if applicable in test data
        for blocks in families.values() {
            assert!(!blocks.is_empty());
        }
    }

    #[test]
    fn blocks_with_complex_properties_work() {
        let requirements = vec![("delay".to_string(), vec!["2".to_string()])];
        let results: Vec<_> = blocks_with_complex_properties(&requirements).collect();
        assert!(!results.is_empty());
    }

    #[test]
    fn analyze_property_correlation_accuracy() {
        let correlations = analyze_property_correlation();
        assert!(!correlations.is_empty());
    }

    #[test]
    fn find_similar_blocks_effective() {
        // Test with a low threshold since our test dataset is small
        let similar_blocks = find_similar_blocks("minecraft:repeater", 1);

        // In our small test dataset, there might not be other blocks with shared properties
        // So let's just verify the function works and returns a valid result
        // (length is always >= 0, but we're testing the function returns something)

        // Test with a block that doesn't exist
        let non_existent = find_similar_blocks("minecraft:nonexistent", 1);
        assert!(non_existent.is_empty());

        // Test the function structure is working
        for (block, shared_properties) in similar_blocks {
            println!(
                "Block: {}, Shared Properties: {}",
                block.id(),
                shared_properties
            );
            assert!(shared_properties >= 1); // Should have at least the minimum
        }
    }

    #[test]
    fn get_advanced_property_stats_correct() {
        let stats = get_advanced_property_stats();
        assert!(stats.basic_stats.total_unique_properties > 0);

        println!(
            "Most diverse property: {} with {} values",
            stats.most_diverse_property.0, stats.most_diverse_property.1
        );
        println!(
            "Most correlated properties: {:?}",
            stats.most_correlated_properties
        );
    }
}

#[cfg(test)]
mod milestone2_tests {
    use crate::{BlockState, BLOCKS};

    #[test]
    fn phf_table_loads_successfully() {
        assert!(BLOCKS.len() >= 3);
        assert!(BLOCKS.get("minecraft:stone").is_some());
    }

    #[test]
    fn block_facts_has_expected_data() {
        let stone = BLOCKS.get("minecraft:stone").unwrap();
        assert_eq!(stone.id(), "minecraft:stone");
        assert!(stone.properties().is_empty()); // Stone has no properties in our test

        let repeater = BLOCKS.get("minecraft:repeater").unwrap();
        assert!(repeater.has_property("delay"));
        assert_eq!(
            repeater.get_property_values("delay"),
            Some(vec![
                "1".to_string(),
                "2".to_string(),
                "3".to_string(),
                "4".to_string()
            ])
        );
    }

    #[test]
    fn block_state_creates_successfully() {
        let state = BlockState::new("minecraft:stone").unwrap();
        assert_eq!(state.to_string(), "minecraft:stone");

        let state = BlockState::new("nonexistent:block");
        assert!(state.is_err());
    }

    #[test]
    fn block_state_with_properties() {
        let state = BlockState::new("minecraft:repeater")
            .unwrap()
            .with("delay", "3")
            .unwrap();
        assert!(state.to_string().contains("delay=3"));
    }
}

#[cfg(test)]
mod milestone3_tests {
    use crate::{BlockState, BLOCKS};

    #[test]
    fn valid_properties_accepted() {
        let valid = BlockState::new("minecraft:repeater")
            .unwrap()
            .with("delay", "2")
            .unwrap()
            .with("facing", "north")
            .unwrap();
        assert!(valid.to_string().contains("delay=2"));
        assert!(valid.to_string().contains("facing=north"));
    }

    #[test]
    fn invalid_property_values_rejected() {
        let result = BlockState::new("minecraft:repeater")
            .unwrap()
            .with("delay", "5"); // Invalid: only 1-4 allowed
        assert!(result.is_err());
        let error_msg = result.unwrap_err().to_string();
        assert!(error_msg.contains("Invalid value '5'"));

        let result = BlockState::new("minecraft:repeater")
            .unwrap()
            .with("nonexistent_prop", "value");
        assert!(result.is_err());
        let error_msg = result.unwrap_err().to_string();
        assert!(error_msg.contains("does not have property") || error_msg.contains("not found"));
    }

    #[test]
    fn property_case_sensitivity() {
        // Property names should be case sensitive
        let result = BlockState::new("minecraft:repeater")
            .unwrap()
            .with("Delay", "1"); // Wrong case
        assert!(result.is_err());

        // Values should be case sensitive too
        let result = BlockState::new("minecraft:repeater")
            .unwrap()
            .with("facing", "North"); // Wrong case
        assert!(result.is_err());
    }

    #[test]
    fn default_state_roundtrip() {
        let block = BLOCKS.get("minecraft:repeater").unwrap();
        let default_state = BlockState::from_default(block).unwrap();
        let rebuilt = BlockState::parse(&default_state.to_string()).unwrap();
        assert_eq!(default_state.to_string(), rebuilt.to_string());
    }

    #[test]
    fn unknown_block_rejected() {
        let result = BlockState::new("minecraft:nonexistent_block");
        assert!(result.is_err());
        let error_msg = result.unwrap_err().to_string();
        assert!(error_msg.contains("not found"));
    }

    #[test]
    fn parse_blockstate_string() {
        // Test parsing simple block
        let state = BlockState::parse("minecraft:stone").unwrap();
        assert_eq!(state.to_string(), "minecraft:stone");

        // Test parsing block with properties
        let state = BlockState::parse("minecraft:repeater[delay=3,facing=south]").unwrap();
        assert!(state.to_string().contains("delay=3"));
        assert!(state.to_string().contains("facing=south"));

        // Test invalid format
        let result = BlockState::parse("minecraft:repeater[delay=3,facing=south"); // Missing ]
        assert!(result.is_err());
    }
}

#[cfg(test)]
mod milestone4_tests {
    use crate::{queries::*, BLOCKS};

    #[test]
    fn find_blocks_by_property_works() {
        // Test with waterlogged property (if it exists in our test data)
        let _waterloggable: Vec<_> = find_blocks_by_property("waterlogged", "true").collect();
        // Since our test data might not have waterlogged blocks, let's test with what we have

        // Test with delay property that we know exists
        let delay_blocks: Vec<_> = find_blocks_by_property("delay", "1").collect();
        assert!(delay_blocks.iter().any(|b| b.id() == "minecraft:repeater"));
    }

    #[test]
    fn find_blocks_matching_predicate() {
        let complex_redstone: Vec<_> = find_blocks_matching(|block| {
            block.has_property("powered") && block.has_property("facing")
        })
        .collect();

        assert!(complex_redstone
            .iter()
            .any(|b| b.id() == "minecraft:repeater"));
    }

    #[test]
    fn search_blocks_pattern_matching() {
        // Test exact match
        let stone_blocks: Vec<_> = search_blocks("stone").collect();
        assert!(stone_blocks.iter().any(|b| b.id() == "minecraft:stone"));

        // Test wildcard pattern
        let minecraft_blocks: Vec<_> = search_blocks("minecraft:*").collect();
        assert!(minecraft_blocks.len() >= 3); // Should match all our test blocks
    }

    #[test]
    fn get_property_values_comprehensive() {
        let delay_values = get_property_values("delay").unwrap();
        assert_eq!(delay_values, vec!["1", "2", "3", "4"]);

        let facing_values = get_property_values("facing").unwrap();
        assert!(facing_values.contains(&"north".to_string()));
        assert!(facing_values.len() >= 4); // At least cardinal directions
    }

    #[test]
    fn count_blocks_where_accurate() {
        let total_blocks = BLOCKS.len();
        let counted = count_blocks_where(|_| true);
        assert_eq!(total_blocks, counted);

        let blocks_with_properties = count_blocks_where(|b| !b.properties.is_empty());
        assert!(blocks_with_properties >= 1); // At least repeater has properties
    }

    #[test]
    fn get_block_families_logical() {
        let families = get_block_families();

        // Our test data doesn't have many families, but let's test the logic
        assert!(!families.is_empty());

        // Each family should have at least one block
        for blocks in families.values() {
            assert!(!blocks.is_empty());
        }
    }

    #[test]
    fn blocks_with_properties_works() {
        let results: Vec<_> = blocks_with_properties(&[
            ("delay", "*"),      // Any delay value
            ("facing", "north"), // Specific facing value
        ])
        .collect();

        // Should find repeater when it has both delay and facing=north in defaults
        assert!(!results.is_empty());

        // All results should have both properties
        for block in results {
            assert!(block.has_property("delay"));
            assert!(block.has_property("facing"));
        }
    }

    #[test]
    fn find_rare_properties_works() {
        let rare = find_rare_properties(0.5); // Properties in <50% of blocks

        // Most properties should be rare in our small test set
        assert!(!rare.is_empty());

        // Each property should have a count
        for count in rare.values() {
            assert!(*count > 0);
        }
    }

    #[test]
    fn property_statistics_accurate() {
        let stats = get_property_stats();

        assert!(stats.total_unique_properties > 0);
        assert!(stats.most_common_property.1 > 0); // Most common property appears at least once
        assert!(stats.blocks_with_no_properties >= 1); // Stone has no properties
        assert!(stats.average_properties_per_block >= 0.0);
    }
}

#[cfg(test)]
mod bedrock_translation_tests {
    use crate::{BlockState, BLOCKS};
    use std::collections::HashMap;

    #[test]
    fn redstone_wire_java_to_bedrock() {
        // Only run if redstone_wire exists in the current data
        if let Some(java_facts) = BLOCKS.get("minecraft:redstone_wire") {
            let java_state = BlockState::from_default(java_facts)
                .unwrap()
                .with("power", "15")
                .unwrap();

            let bedrock_state = java_state.to_bedrock().unwrap();

            assert_eq!(bedrock_state.id(), "minecraft:redstone_wire");
            assert_eq!(bedrock_state.get_property("redstone_signal"), Some("15"));
        }
    }

    #[test]
    fn redstone_wire_bedrock_to_java() {
        // Only run if redstone_wire has Bedrock mapping
        let java_facts = BLOCKS
            .values()
            .find(|f| f.id == "minecraft:redstone_wire" && f.extras.bedrock.is_some());

        if java_facts.is_some() {
            let mut bedrock_props = HashMap::new();
            bedrock_props.insert("redstone_signal".to_string(), "15".to_string());

            let java_state =
                BlockState::from_bedrock("minecraft:redstone_wire", bedrock_props).unwrap();

            assert_eq!(java_state.id(), "minecraft:redstone_wire");
            assert_eq!(java_state.get_property("power"), Some("15"));
        }
    }

    #[test]
    fn repeater_java_to_bedrock_facing() {
        if let Some(java_facts) = BLOCKS.get("minecraft:repeater") {
            let java_state = BlockState::from_default(java_facts)
                .unwrap()
                .with("facing", "north")
                .unwrap()
                .with("powered", "false")
                .unwrap();

            // Check if it has bedrock data
            if java_facts.extras.bedrock.is_some() {
                let bedrock_state = java_state.to_bedrock().unwrap();
                // Java "repeater" + "powered=false" -> Bedrock "unpowered_repeater"
                assert_eq!(bedrock_state.id(), "minecraft:unpowered_repeater");
                // Java "north" -> Bedrock cardinal_direction "north" (for repeaters)
                assert_eq!(
                    bedrock_state.get_property("minecraft:cardinal_direction"),
                    Some("north")
                );
            }
        }
    }

    #[test]
    fn powered_repeater_java_to_bedrock() {
        if let Some(java_facts) = BLOCKS.get("minecraft:repeater") {
            let java_state = BlockState::from_default(java_facts)
                .unwrap()
                .with("powered", "true")
                .unwrap();

            if java_facts.extras.bedrock.is_some() {
                let bedrock_state = java_state.to_bedrock().unwrap();
                // Java "repeater" + "powered=true" -> Bedrock "powered_repeater"
                assert_eq!(bedrock_state.id(), "minecraft:powered_repeater");
            }
        }
    }

    #[test]
    fn wall_torch_java_to_bedrock() {
        if let Some(java_facts) = BLOCKS.get("minecraft:wall_torch") {
            let java_state = BlockState::from_default(java_facts)
                .unwrap()
                .with("facing", "north")
                .unwrap();

            if java_facts.extras.bedrock.is_some() {
                let bedrock_state = java_state.to_bedrock().unwrap();
                // Java "wall_torch" -> Bedrock "torch"
                assert_eq!(bedrock_state.id(), "minecraft:torch");
                // Java "facing=north" -> Bedrock "torch_facing_direction=south"
                assert_eq!(
                    bedrock_state.get_property("torch_facing_direction"),
                    Some("south")
                );
            }
        }
    }

    #[test]
    fn bedrock_torch_to_java() {
        // Bedrock side torch
        let mut props = HashMap::new();
        props.insert("torch_facing_direction".to_string(), "south".to_string());

        let java_state = BlockState::from_bedrock("minecraft:torch", props).unwrap();
        // Bedrock "torch" + "south" -> Java "wall_torch" + "north"
        assert_eq!(java_state.id(), "minecraft:wall_torch");
        assert_eq!(java_state.get_property("facing"), Some("north"));

        // Bedrock top torch
        let mut props = HashMap::new();
        props.insert("torch_facing_direction".to_string(), "top".to_string());

        let java_state = BlockState::from_bedrock("minecraft:torch", props).unwrap();
        // Bedrock "torch" + "top" -> Java "torch"
        assert_eq!(java_state.id(), "minecraft:torch");
    }

    #[test]
    fn stairs_java_to_bedrock_half() {
        if let Some(java_facts) = BLOCKS.get("minecraft:oak_stairs") {
            let java_state = BlockState::from_default(java_facts)
                .unwrap()
                .with("half", "top")
                .unwrap();

            if java_facts.extras.bedrock.is_some() {
                let bedrock_state = java_state.to_bedrock().unwrap();
                // Java "half=top" -> Bedrock "upside_down_bit=true"
                assert_eq!(bedrock_state.get_property("upside_down_bit"), Some("true"));
            }
        }
    }

    #[test]
    fn door_java_to_bedrock_half() {
        if let Some(java_facts) = BLOCKS.get("minecraft:oak_door") {
            let java_state = BlockState::from_default(java_facts)
                .unwrap()
                .with("half", "upper")
                .unwrap();

            if java_facts.extras.bedrock.is_some() {
                let bedrock_state = java_state.to_bedrock().unwrap();
                // Java "half=upper" -> Bedrock "upper_block_bit=true"
                assert_eq!(bedrock_state.get_property("upper_block_bit"), Some("true"));
            }
        }
    }

    // ────────────────────────────────────────────────────────────────────
    // Redstone-relevant Java→Bedrock translations (BP-1 batch)
    // Added after a community report showed hoppers/pistons/repeaters
    // losing orientation on `.mcstructure` export.
    // ────────────────────────────────────────────────────────────────────

    /// Helper: build a Java state with a list of (k, v) properties.
    fn java_state(id: &str, props: &[(&str, &str)]) -> Option<BlockState> {
        let facts = BLOCKS.get(id)?;
        if facts.extras.bedrock.is_none() {
            return None;
        }
        let mut s = BlockState::from_default(facts).ok()?;
        for (k, v) in props {
            s = s.with(k, v).ok()?;
        }
        Some(s)
    }

    #[test]
    fn hopper_java_to_bedrock_facing_north() {
        if let Some(j) = java_state("minecraft:hopper", &[("facing", "north")]) {
            let b = j.to_bedrock().unwrap();
            assert_eq!(b.id(), "minecraft:hopper");
            // Bedrock facing_direction: 0=down, 1=up, 2=north, 3=south, 4=west, 5=east
            assert_eq!(
                b.get_property("facing_direction"),
                Some("2"),
                "hopper north -> facing_direction=2; got {:?}",
                b.properties()
            );
        }
    }

    #[test]
    fn hopper_java_to_bedrock_all_facings() {
        // Map of Java facing → expected Bedrock facing_direction
        let cases = &[
            ("down", "0"),
            ("north", "2"),
            ("south", "3"),
            ("west", "4"),
            ("east", "5"),
        ];
        for (java_facing, expected_dir) in cases {
            if let Some(j) = java_state("minecraft:hopper", &[("facing", java_facing)]) {
                let b = j.to_bedrock().unwrap();
                assert_eq!(
                    b.get_property("facing_direction"),
                    Some(*expected_dir),
                    "hopper facing={} -> expected facing_direction={}, got {:?}",
                    java_facing,
                    expected_dir,
                    b.properties()
                );
            }
        }
    }

    #[test]
    fn sticky_piston_java_to_bedrock_facings() {
        // Piston facing_direction in Bedrock is INVERTED on the horizontal
        // plane relative to other blocks. This matches Geyser's mapping —
        // Bedrock semantics is "direction the back of the piston faces"
        // while Java is "direction the head faces". So Java north ↔
        // Bedrock 3 (south), east ↔ 4 (east no change because of east/west
        // mirror), etc.
        let cases = &[
            ("down", "0"),
            ("up", "1"),
            ("north", "3"),
            ("south", "2"),
            ("west", "5"),
            ("east", "4"),
        ];
        for (java_facing, expected_dir) in cases {
            if let Some(j) = java_state(
                "minecraft:sticky_piston",
                &[("facing", java_facing), ("extended", "false")],
            ) {
                let b = j.to_bedrock().unwrap();
                assert!(
                    b.id().contains("sticky_piston"),
                    "expected sticky_piston id, got '{}'",
                    b.id()
                );
                assert_eq!(
                    b.get_property("facing_direction"),
                    Some(*expected_dir),
                    "sticky_piston facing={} -> expected facing_direction={}, got {:?}",
                    java_facing,
                    expected_dir,
                    b.properties()
                );
            }
        }
    }

    #[test]
    fn observer_java_to_bedrock_facing_and_powered() {
        if let Some(j) = java_state(
            "minecraft:observer",
            &[("facing", "east"), ("powered", "true")],
        ) {
            let b = j.to_bedrock().unwrap();
            // Observer in Bedrock uses the namespaced `minecraft:facing_direction`
            // STRING property (not the `facing_direction` integer used by hoppers).
            // Geyser carries Java facing values through unchanged.
            assert!(b.id().contains("observer"), "got id={}", b.id());
            assert_eq!(
                b.get_property("minecraft:facing_direction"),
                Some("east"),
                "observer facing=east -> minecraft:facing_direction=east, got {:?}",
                b.properties()
            );
            assert_eq!(
                b.get_property("powered_bit"),
                Some("true"),
                "observer powered=true -> powered_bit=true, got {:?}",
                b.properties()
            );
        }
    }

    #[test]
    fn comparator_java_to_bedrock_mode_and_facing() {
        if let Some(j) = java_state(
            "minecraft:comparator",
            &[
                ("facing", "north"),
                ("mode", "subtract"),
                ("powered", "true"),
            ],
        ) {
            let b = j.to_bedrock().unwrap();
            // Bedrock comparator splits into `unpowered_comparator` and
            // `powered_comparator` by powered state.
            assert!(
                b.id().contains("comparator"),
                "expected comparator id, got '{}'",
                b.id()
            );
            // Java "subtract" -> Bedrock output_subtract_bit=true
            assert_eq!(
                b.get_property("output_subtract_bit"),
                Some("true"),
                "comparator mode=subtract -> output_subtract_bit=true, got {:?}",
                b.properties()
            );
        }
    }

    #[test]
    fn lever_java_to_bedrock_face_wall() {
        if let Some(j) = java_state(
            "minecraft:lever",
            &[("face", "wall"), ("facing", "east"), ("powered", "true")],
        ) {
            let b = j.to_bedrock().unwrap();
            assert_eq!(b.id(), "minecraft:lever");
            // Bedrock `open_bit` mirrors Java `powered`.
            assert_eq!(
                b.get_property("open_bit"),
                Some("true"),
                "lever powered=true -> open_bit=true, got {:?}",
                b.properties()
            );
        }
    }

    #[test]
    fn furnace_java_to_bedrock_facing_and_lit() {
        if let Some(j) = java_state(
            "minecraft:furnace",
            &[("facing", "south"), ("lit", "true")],
        ) {
            let b = j.to_bedrock().unwrap();
            // Bedrock furnace splits into `lit_furnace` / `furnace` by lit state
            // and uses the namespaced string `minecraft:cardinal_direction`
            // property (not facing_direction).
            assert!(b.id().contains("furnace"), "got id={}", b.id());
            assert_eq!(
                b.get_property("minecraft:cardinal_direction"),
                Some("south"),
                "furnace facing=south -> minecraft:cardinal_direction=south, got {:?}",
                b.properties()
            );
        }
    }

    #[test]
    fn dispenser_java_to_bedrock_facing_and_triggered() {
        if let Some(j) = java_state(
            "minecraft:dispenser",
            &[("facing", "down"), ("triggered", "true")],
        ) {
            let b = j.to_bedrock().unwrap();
            assert_eq!(b.id(), "minecraft:dispenser");
            assert_eq!(
                b.get_property("facing_direction"),
                Some("0"),
                "dispenser facing=down -> facing_direction=0, got {:?}",
                b.properties()
            );
            assert_eq!(
                b.get_property("triggered_bit"),
                Some("true"),
                "dispenser triggered=true -> triggered_bit=true, got {:?}",
                b.properties()
            );
        }
    }

    #[test]
    fn dropper_java_to_bedrock_facing() {
        if let Some(j) = java_state(
            "minecraft:dropper",
            &[("facing", "up"), ("triggered", "false")],
        ) {
            let b = j.to_bedrock().unwrap();
            assert_eq!(b.id(), "minecraft:dropper");
            assert_eq!(
                b.get_property("facing_direction"),
                Some("1"),
                "dropper facing=up -> facing_direction=1, got {:?}",
                b.properties()
            );
        }
    }
}