lazydns 0.2.63

A light and fast DNS server/forwarder implementation in Rust
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
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
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
//! Plugin builder system
//!
//! This module provides a builder pattern for creating plugin instances from configuration.
//! It supports both the new Plugin trait pattern and legacy hardcoded plugins.

use crate::Error;
use crate::Result;
use crate::config::types::PluginConfig;
use crate::dns_type_match;
use crate::plugin::traits::Matcher;
use crate::plugin::{Context, Plugin};
use crate::plugins::executable::SequenceStep;
use crate::plugins::*;
use serde_yaml::Value;
use std::collections::HashMap;
use std::sync::Arc;
use tracing::trace;
use tracing::{debug, error, info, warn};

// ============================================================================
// Main Plugin Builder (Configuration-based Plugin Creation)
// ============================================================================

/// Plugin builder that creates plugin instances from configuration
pub struct PluginBuilder {
    /// Registry of named plugins for reference
    plugins: HashMap<String, Arc<dyn Plugin>>,
    /// Server plugin tags
    server_plugin_tags: Vec<String>,
}

impl PluginBuilder {
    /// Create a new plugin builder
    pub fn new() -> Self {
        // Initialize plugin builder system
        // Ensure plugin builders from plugin modules are initialized (register themselves)
        info!("Initializing plugin builder system...");
        crate::plugin::factory::init();

        Self {
            plugins: HashMap::new(),
            server_plugin_tags: Vec::new(),
        }
    }

    /// Build a plugin from configuration
    pub fn build(&mut self, config: &PluginConfig) -> Result<Arc<dyn Plugin>> {
        // Normalize plugin type for more forgiving parsing (trim and lowercase)
        let plugin_type = config.plugin_type.trim().to_lowercase();

        // Try to get builder from registry first
        if let Some(builder) = crate::plugin::factory::get_plugin_factory(&plugin_type) {
            trace!(
                name = %config.effective_name(),
                plugin_type = %plugin_type,
                "Creating plugin using registered builder"
            );
            let plugin = builder.create(config)?;

            // Store in registry if it has a tag or name
            let effective_name = config.effective_name().to_string();
            self.plugins.insert(effective_name, Arc::clone(&plugin));

            return Ok(plugin);
        }

        // Fallback to legacy hardcoded match for backward compatibility
        trace!(
            name = %config.effective_name(),
            plugin_type = %plugin_type,
            "Plugin type not found in builder registry, using legacy match",
        );

        let plugin: Arc<dyn Plugin> = match plugin_type.as_str() {
            "sequence" => {
                // Handle different sequence formats
                if let Value::Mapping(map) = &config.args {
                    // Check if args contains "plugins" key (simple format)
                    if let Some(plugins_value) = map.get(Value::String("plugins".to_string())) {
                        if let Value::Sequence(plugin_names) = plugins_value {
                            let plugins = Vec::new();
                            for name_value in plugin_names {
                                if let Value::String(_name) = name_value {
                                    // We'll resolve plugin references in a second pass
                                    // For now, store the name and resolve later
                                    // This is a placeholder - actual resolution needs to be implemented
                                    warn!(
                                        "Sequence plugin with 'plugins' key not fully implemented yet"
                                    );
                                }
                            }
                            Arc::new(SequencePlugin::new(plugins))
                        } else {
                            return Err(Error::Config(
                                "sequence 'plugins' must be an array".to_string(),
                            ));
                        }
                    } else {
                        // Other mapping formats - not implemented yet
                        warn!(
                            "Sequence plugin mapping format not implemented yet, using empty sequence"
                        );
                        Arc::new(SequencePlugin::new(Vec::new()))
                    }
                } else if let Value::Sequence(sequence) = &config.args {
                    // Complex format - parse the steps
                    match parse_sequence_steps(self, sequence) {
                        Ok(steps) => Arc::new(SequencePlugin::with_steps(steps)),
                        Err(e) => {
                            warn!(
                                "Failed to parse complex sequence: {}, using empty sequence",
                                e
                            );
                            Arc::new(SequencePlugin::new(Vec::new()))
                        }
                    }
                } else {
                    // Other formats
                    warn!("Sequence plugin args format not recognized, using empty sequence");
                    Arc::new(SequencePlugin::new(Vec::new()))
                }
            }

            // Accept tcp/udp/doh/dot/doq server plugin types at build time so configuration
            // parsing succeeds. The actual servers are started by the application
            // runtime (launcher.rs). Here we return
            // a benign plugin instance (AcceptPlugin) so the name is registered
            // and can be referenced by other plugins.
            "tcp_server" | "udp_server" | "doh_server" | "dot_server" | "doq_server" => {
                let tag = config.effective_name().to_string();
                self.server_plugin_tags.push(tag.clone());
                Arc::new(crate::plugins::AcceptPlugin::new())
            }

            _ => {
                return Err(Error::Config(format!(
                    "Unknown plugin type: {}",
                    plugin_type
                )));
            }
        };

        // Store in registry if it has a tag or name
        let effective_name = config.effective_name().to_string();
        self.plugins.insert(effective_name, Arc::clone(&plugin));

        Ok(plugin)
    }

    /// After building all plugins, resolve any references between plugins
    /// (for example, `fallback` refers to other plugins by name).
    /// This also re-parses sequences to update plugin references after fallback resolution.
    pub fn resolve_references(&mut self, configs: &[PluginConfig]) -> Result<()> {
        // First pass: update sequence plugins to reflect resolved plugins
        for config in configs {
            if config.plugin_type == "sequence"
                && let Value::Sequence(sequence) = &config.args
            {
                // Re-parse the steps with the now-resolved plugins
                match parse_sequence_steps(self, sequence) {
                    Ok(steps) => {
                        // Preserve the configured tag when creating the resolved sequence
                        let sequence_plugin = Arc::new(SequencePlugin::with_steps_and_tag(
                            steps,
                            config.tag.clone(),
                        ));
                        let name = config.effective_name().to_string();
                        let dname = sequence_plugin.display_name().to_string();
                        self.plugins.insert(name.clone(), sequence_plugin);
                        trace!(
                            "Updated sequence plugin '{}' with resolved references (display={})",
                            name, dname
                        );
                    }
                    Err(e) => {
                        warn!(
                            "Failed to update sequence '{}': {}",
                            config.effective_name(),
                            e
                        );
                    }
                }
            }
        }

        // Second pass: ask fallback plugins to resolve their pending child references
        for config in configs {
            if config.plugin_type == "fallback" {
                let name = config.effective_name().to_string();
                debug!("Resolving fallback plugin: {}", name);
                if let Some(plugin) = self.plugins.get(&name).cloned() {
                    // Attempt to downcast to FallbackPlugin and let it resolve itself
                    if let Some(fp) = plugin.as_ref().as_any().downcast_ref::<FallbackPlugin>() {
                        fp.resolve_children(&self.plugins);
                    } else {
                        warn!(plugin = %name, "Plugin registered under name is not a FallbackPlugin");
                    }
                } else {
                    warn!(plugin = %name, "Fallback plugin not found in registry");
                }
            }
        }

        Ok(())
    }

    /// Get a plugin by name from the registry
    pub fn get_plugin(&self, name: &str) -> Option<Arc<dyn Plugin>> {
        self.plugins.get(name).cloned()
    }

    /// Get all plugins
    pub fn get_all_plugins(&self) -> Vec<Arc<dyn Plugin>> {
        self.plugins.values().cloned().collect()
    }

    /// Convert the builder's plugin map into a Registry
    pub fn into_registry(self) -> crate::plugin::Registry {
        let mut registry = crate::plugin::Registry::new();
        for (name, plugin) in self.plugins {
            registry.register_replace_with_name(&name, plugin);
        }
        registry
    }

    /// Get a Registry containing all plugins (clone-based)
    pub fn get_registry(&self) -> crate::plugin::Registry {
        let mut registry = crate::plugin::Registry::new();
        for (name, plugin) in &self.plugins {
            registry.register_replace_with_name(name, Arc::clone(plugin));
        }
        registry
    }

    /// Get server plugin tags
    pub fn get_server_plugin_tags(&self) -> &[String] {
        &self.server_plugin_tags
    }

    /// Shutdown all plugins
    ///
    /// This method iterates through all registered plugins and calls their
    /// shutdown method for graceful cleanup.
    ///
    /// # Returns
    ///
    /// Returns `Ok(())` if all plugins shut down successfully, or the first
    /// error encountered during shutdown.
    pub async fn shutdown_all(&self) -> Result<()> {
        for (name, plugin) in &self.plugins {
            if let Some(sh) = plugin.as_shutdown() {
                info!("Shutting down plugin: {}", name);
                if let Err(e) = sh.shutdown().await {
                    error!("Error shutting down plugin {}: {}", name, e);
                    return Err(e);
                }
            }
        }
        Ok(())
    }

    /// Start background tasks for plugins that need them
    ///
    /// This method iterates through all registered plugins and starts any
    /// background tasks they may require (e.g., cache cleanup tasks).
    ///
    /// # Returns
    ///
    /// Returns a vector of JoinHandles for the spawned background tasks.
    pub fn start_background_tasks(&self) -> Vec<tokio::task::JoinHandle<()>> {
        let mut background_tasks = Vec::new();

        for (plugin_name, plugin) in &self.plugins {
            // Check if this is a CachePlugin and start its cleanup task
            if plugin
                .as_any()
                .downcast_ref::<CachePlugin>()
                .is_some_and(|cache_plugin| cache_plugin.is_cleanup_enabled())
            {
                let cache_plugin = plugin.as_any().downcast_ref::<CachePlugin>().unwrap();
                info!(
                    "Starting background cleanup task for cache plugin '{}'",
                    plugin_name
                );
                // Clone the plugin and wrap in Arc
                let cache_arc = Arc::new((*cache_plugin).clone());
                let cleanup_handle = cache_arc.spawn_cleanup_task();
                background_tasks.push(cleanup_handle);
            }
        }

        background_tasks
    }
}

impl Default for PluginBuilder {
    fn default() -> Self {
        Self::new()
    }
}

/// Parse complex sequence steps from YAML sequence
fn parse_sequence_steps(builder: &PluginBuilder, sequence: &[Value]) -> Result<Vec<SequenceStep>> {
    use crate::plugins::executable::SequenceStep;
    trace!("Parsing {} sequence steps", sequence.len());
    let mut steps = Vec::new();

    for step_value in sequence {
        match step_value {
            Value::Mapping(map) => {
                // Check if it's a conditional step (has "matches" key)
                if let Some(matches_value) = map.get(Value::String("matches".to_string())) {
                    if let Value::String(condition_str) = matches_value {
                        // Parse condition
                        let condition = parse_condition(builder, condition_str)?;

                        // Get the exec action
                        if let Some(exec_value) = map.get(Value::String("exec".to_string())) {
                            let action = parse_exec_action(builder, exec_value)?;
                            steps.push(SequenceStep::If {
                                condition,
                                action,
                                desc: condition_str.to_string(),
                            });
                        } else {
                            return Err(Error::Config("matches step must have exec".to_string()));
                        }
                    } else {
                        return Err(Error::Config("matches value must be string".to_string()));
                    }
                } else if let Some(exec_value) = map.get(Value::String("exec".to_string())) {
                    // Simple exec step
                    let plugin = parse_exec_action(builder, exec_value)?;
                    steps.push(SequenceStep::Exec(plugin));
                } else {
                    return Err(Error::Config(
                        "sequence step must have exec or matches".to_string(),
                    ));
                }
            }
            _ => return Err(Error::Config("sequence step must be a mapping".to_string())),
        }
    }

    Ok(steps)
}

/// Parse exec action from YAML value
fn parse_exec_action(builder: &PluginBuilder, exec_value: &Value) -> Result<Arc<dyn Plugin>> {
    match exec_value {
        Value::String(exec_str) => {
            // First try to parse as exec plugin: prefix [exec_str]
            let (prefix, exec_args) = if let Some(space_pos) = exec_str.find(' ') {
                let (p, rest) = exec_str.split_at(space_pos);
                (p.trim(), rest.trim())
            } else {
                (exec_str.as_str(), "")
            };

            // Try exec plugin registry first
            if let Some(factory) = crate::plugin::factory::get_exec_plugin_factory(prefix) {
                return factory.create(prefix, exec_args);
            }

            // Handle different exec formats
            if let Some(plugin_name) = exec_str.strip_prefix('$') {
                // Plugin reference: $plugin_name
                if let Some(plugin) = builder.get_plugin(plugin_name) {
                    Ok(plugin)
                } else {
                    Err(Error::Config(format!(
                        "Referenced plugin '{}' not found",
                        plugin_name
                    )))
                }
            } else {
                Err(Error::Config(format!("Unknown exec action: {}", exec_str)))
            }
        }
        _ => Err(Error::Config("exec value must be string".to_string())),
    }
}
#[allow(clippy::type_complexity)]
fn parse_condition(
    builder: &PluginBuilder,
    condition_str: &str,
) -> Result<Arc<dyn Fn(&Context) -> bool + Send + Sync>> {
    use crate::plugin::condition::builder::get_condition_builder_registry;

    // Get the condition builder registry
    let registry = get_condition_builder_registry();

    // Try to find a builder for this condition
    if let Some(condition_builder) = registry.get_builder(condition_str) {
        condition_builder.build(condition_str, builder)
    } else {
        // Unsupported condition
        Err(Error::Config(format!(
            "Unknown condition: {}",
            condition_str
        )))
    }
}

/// Legacy hardcoded condition parsing (fallback for backward compatibility)
#[allow(clippy::type_complexity, dead_code)]
#[deprecated(
    since = "0.2.43",
    note = "Legacy condition parsing is deprecated. Please use the new condition builder framework."
)]
fn legacy_parse_condition(
    builder: &PluginBuilder,
    condition_str: &str,
) -> Result<Arc<dyn Fn(&Context) -> bool + Send + Sync>> {
    // Legacy implementation - all conditions are now handled by builders
    // This function is kept for backward compatibility and can be removed
    // once all conditions are migrated to the builder framework

    if condition_str == "has_resp" {
        Ok(Arc::new(|ctx: &crate::plugin::Context| ctx.has_response()))
    } else if let Some(ip_set_ref) = condition_str.strip_prefix("resp_ip ") {
        let ip_set_name = if let Some(name) = ip_set_ref.strip_prefix('$') {
            name
        } else {
            ip_set_ref
        };
        // Get the IP set plugin and create a matcher
        if let Some(plugin) = builder.get_plugin(ip_set_name) {
            if plugin.name() == "ip_set" {
                let plugin_clone = Arc::clone(&plugin);
                Ok(Arc::new(move |ctx: &crate::plugin::Context| {
                    if let Some(matcher) = plugin_clone
                        .as_ref()
                        .as_any()
                        .downcast_ref::<crate::plugins::dataset::IpSetPlugin>()
                    {
                        matcher.matches_context(ctx)
                    } else {
                        false
                    }
                }))
            } else {
                warn!("Plugin '{}' is not an IP set plugin", ip_set_name);
                Ok(Arc::new(|_ctx: &crate::plugin::Context| false))
            }
        } else {
            warn!("IP set plugin '{}' not found", ip_set_name);
            Ok(Arc::new(|_ctx: &crate::plugin::Context| false))
        }
    } else if let Some(ip_set_ref) = condition_str.strip_prefix("!resp_ip ") {
        let ip_set_name = if let Some(name) = ip_set_ref.strip_prefix('$') {
            name
        } else {
            ip_set_ref
        };
        // Negated IP matching
        if let Some(plugin) = builder.get_plugin(ip_set_name) {
            if plugin.name() == "ip_set" {
                let plugin_clone = Arc::clone(&plugin);
                Ok(Arc::new(move |ctx: &crate::plugin::Context| {
                    if let Some(matcher) = plugin_clone
                        .as_ref()
                        .as_any()
                        .downcast_ref::<crate::plugins::dataset::IpSetPlugin>()
                    {
                        !matcher.matches_context(ctx)
                    } else {
                        true
                    }
                }))
            } else {
                warn!("Plugin '{}' is not an IP set plugin", ip_set_name);
                Ok(Arc::new(|_ctx: &crate::plugin::Context| true))
            }
        } else {
            warn!("IP set plugin '{}' not found", ip_set_name);
            Ok(Arc::new(|_ctx: &crate::plugin::Context| true))
        }
    } else if let Some(domain_set_ref) = condition_str.strip_prefix("qname ") {
        let domain_set_name = if let Some(name) = domain_set_ref.strip_prefix('$') {
            name
        } else {
            domain_set_ref
        };
        // Domain matching
        if let Some(plugin) = builder.get_plugin(domain_set_name) {
            if plugin.name() == "domain_set" {
                let plugin_clone = Arc::clone(&plugin);
                Ok(Arc::new(move |ctx: &crate::plugin::Context| {
                    if let Some(matcher) = plugin_clone
                        .as_ref()
                        .as_any()
                        .downcast_ref::<crate::plugins::dataset::DomainSetPlugin>(
                    ) {
                        matcher.matches_context(ctx)
                    } else {
                        false
                    }
                }))
            } else {
                warn!("Plugin '{}' is not a domain set plugin", domain_set_name);
                Ok(Arc::new(|_ctx: &crate::plugin::Context| false))
            }
        } else {
            warn!("Domain set plugin '{}' not found", domain_set_name);
            Ok(Arc::new(|_ctx: &crate::plugin::Context| false))
        }
    } else if let Some(domain) = condition_str.strip_prefix("!qname ") {
        // Negated domain matching - for single domain, not domain set
        let domain_lower = domain.to_lowercase();
        Ok(Arc::new(move |ctx: &crate::plugin::Context| {
            if let Some(question) = ctx.request().questions().first() {
                let qname = question.qname().to_string().to_lowercase();
                !qname.eq(&domain_lower)
            } else {
                true
            }
        }))
    } else if condition_str.starts_with("qtype ") {
        // qtype 12 65 - query type matching
        let type_str = condition_str.strip_prefix("qtype ").unwrap_or_default();
        let mut qtypes = Vec::new();

        // Parse space-separated type numbers
        for type_part in type_str.split_whitespace() {
            match type_part.parse::<u16>() {
                Ok(qtype_num) => {
                    qtypes.push(qtype_num);
                }
                Err(_) => {
                    return Err(Error::Config(format!(
                        "Invalid query type number '{}': {}",
                        type_part, condition_str
                    )));
                }
            }
        }

        if qtypes.is_empty() {
            return Err(Error::Config(format!(
                "No query types specified: {}",
                condition_str
            )));
        }

        Ok(Arc::new(move |ctx: &crate::plugin::Context| {
            if let Some(question) = ctx.request().questions().first() {
                let qtype = question.qtype().to_u16();
                qtypes.contains(&qtype)
            } else {
                false
            }
        }))
    } else if condition_str.starts_with("qclass ") {
        // qclass IN CH HS - query class matching
        let class_str = condition_str.strip_prefix("qclass ").unwrap_or_default();
        let mut qclasses = Vec::new();

        // Parse space-separated class names
        for class_part in class_str.split_whitespace() {
            let class_val =
                dns_type_match!(class_part, u16, "IN" => 1u16, "CH" => 3u16, "HS" => 4u16)
                    .map_err(|_| {
                        Error::Config(format!(
                            "Invalid query class '{}': {}",
                            class_part, condition_str
                        ))
                    })?;
            qclasses.push(class_val);
        }

        if qclasses.is_empty() {
            return Err(Error::Config(format!(
                "No query classes specified: {}",
                condition_str
            )));
        }

        Ok(Arc::new(move |ctx: &crate::plugin::Context| {
            if let Some(question) = ctx.request().questions().first() {
                let qclass = question.qclass().to_u16();
                qclasses.contains(&qclass)
            } else {
                false
            }
        }))
    } else if condition_str.starts_with("rcode ") {
        // rcode NOERROR NXDOMAIN - response code matching
        let rcode_str = condition_str.strip_prefix("rcode ").unwrap_or_default();
        let mut rcodes = Vec::new();

        // Parse space-separated response code names
        for rcode_part in rcode_str.split_whitespace() {
            let rcode_val = dns_type_match!(rcode_part, u8,
                "NOERROR" => 0u8,
                "FORMERR" | "FORMDERR" => 1u8,
                "SERVFAIL" => 2u8,
                "NXDOMAIN" | "NXDOM" => 3u8,
                "NOTIMP" | "NOTIMPL" => 4u8,
                "REFUSED" | "REFUSE" => 5u8,
                "YXDOMAIN" | "YXDOM" => 6u8,
                "YXRRSET" => 7u8,
                "NXRRSET" => 8u8,
                "NOTAUTH" | "NOTAUTHZ" => 9u8,
                "NOTZONE" => 10u8
            )
            .map_err(|_| {
                Error::Config(format!(
                    "Invalid response code '{}': {}",
                    rcode_part, condition_str
                ))
            })?;
            rcodes.push(rcode_val);
        }

        if rcodes.is_empty() {
            return Err(Error::Config(format!(
                "No response codes specified: {}",
                condition_str
            )));
        }

        Ok(Arc::new(move |ctx: &crate::plugin::Context| {
            if let Some(response) = ctx.response() {
                let rcode = response.response_code().to_u8();
                rcodes.contains(&rcode)
            } else {
                false
            }
        }))
    } else if condition_str == "has_cname" {
        // has_cname - check if response contains CNAME records
        Ok(Arc::new(|ctx: &crate::plugin::Context| {
            if let Some(response) = ctx.response() {
                response
                    .answers()
                    .iter()
                    .any(|rr| rr.rtype() == crate::dns::types::RecordType::CNAME)
            } else {
                false
            }
        }))
    } else {
        Err(Error::Config(format!(
            "Unknown condition: {}",
            condition_str
        )))
    }
}

#[allow(clippy::items_after_test_module)]
#[cfg(test)]
mod tests {
    use super::*;
    use crate::dns::types::{RecordClass, RecordType, ResponseCode};
    use crate::dns::{Message, Question, RData, ResourceRecord};
    use crate::plugin::Context;
    use serde_yaml::Mapping;

    #[test]
    fn test_plugin_builder_get_plugin() {
        let mut builder = PluginBuilder::new();

        // Test getting non-existent plugin
        assert!(builder.get_plugin("nonexistent").is_none());

        // Add a plugin and test getting it
        let plugin: Arc<dyn Plugin> = Arc::new(crate::plugins::AcceptPlugin::new());
        builder
            .plugins
            .insert("test_plugin".to_string(), plugin.clone());

        let retrieved = builder.get_plugin("test_plugin");
        assert!(retrieved.is_some());
        assert_eq!(retrieved.unwrap().name(), "accept");
    }

    #[test]
    fn test_plugin_builder_get_all_plugins() {
        let mut builder = PluginBuilder::new();

        // Initially empty
        assert_eq!(builder.get_all_plugins().len(), 0);

        // Add some plugins
        let plugin1: Arc<dyn Plugin> = Arc::new(crate::plugins::AcceptPlugin::new());
        let plugin2: Arc<dyn Plugin> =
            Arc::new(crate::plugins::flow::return_plugin::ReturnPlugin::new());
        builder.plugins.insert("plugin1".to_string(), plugin1);
        builder.plugins.insert("plugin2".to_string(), plugin2);

        let all_plugins = builder.get_all_plugins();
        assert_eq!(all_plugins.len(), 2);

        // Check that both plugins are present (order doesn't matter)
        let names: std::collections::HashSet<_> = all_plugins.iter().map(|p| p.name()).collect();
        assert!(names.contains("accept"));
        assert!(names.contains("return"));
    }

    #[test]
    fn test_plugin_builder_into_registry() {
        let mut builder = PluginBuilder::new();

        // Add a plugin
        let plugin: Arc<dyn Plugin> = Arc::new(crate::plugins::AcceptPlugin::new());
        builder
            .plugins
            .insert("test_plugin".to_string(), plugin.clone());

        // Convert to registry
        let registry = builder.into_registry();

        // Verify the plugin is in the registry
        let retrieved = registry.get("test_plugin");
        assert!(retrieved.is_some());
        assert_eq!(retrieved.unwrap().name(), "accept");
    }

    #[test]
    fn test_plugin_builder_get_registry() {
        let mut builder = PluginBuilder::new();

        // Add a plugin
        let plugin: Arc<dyn Plugin> = Arc::new(crate::plugins::AcceptPlugin::new());
        builder
            .plugins
            .insert("test_plugin".to_string(), plugin.clone());

        // Get registry (without consuming builder)
        let registry = builder.get_registry();

        // Verify the plugin is in the registry
        let retrieved = registry.get("test_plugin");
        assert!(retrieved.is_some());
        assert_eq!(retrieved.unwrap().name(), "accept");

        // Verify original builder still has the plugin
        assert!(builder.get_plugin("test_plugin").is_some());
    }

    #[test]
    fn test_plugin_builder_get_server_plugin_tags() {
        let mut builder = PluginBuilder::new();

        // Initially empty
        assert_eq!(builder.get_server_plugin_tags().len(), 0);

        // Add server plugin tags
        builder.server_plugin_tags.push("doh_server".to_string());
        builder.server_plugin_tags.push("dot_server".to_string());

        let tags = builder.get_server_plugin_tags();
        assert_eq!(tags.len(), 2);
        assert!(tags.contains(&"doh_server".to_string()));
        assert!(tags.contains(&"dot_server".to_string()));
    }

    #[tokio::test]
    async fn test_plugin_builder_shutdown_all() {
        let mut builder = PluginBuilder::new();

        // Add a plugin that implements shutdown
        let plugin: Arc<dyn Plugin> = Arc::new(crate::plugins::AcceptPlugin::new());
        builder
            .plugins
            .insert("test_plugin".to_string(), plugin.clone());

        // Shutdown should succeed
        let result = builder.shutdown_all().await;
        assert!(result.is_ok());
    }

    #[test]
    fn test_build_cache_plugin() {
        let mut builder = PluginBuilder::new();
        let mut config_map = HashMap::new();
        config_map.insert("size".to_string(), Value::Number(2048.into()));

        let config = PluginConfig {
            tag: Some("my_cache".to_string()),
            plugin_type: "cache".to_string(),
            args: Value::Mapping(Mapping::new()),
            priority: 100,
            config: config_map,
        };

        let plugin = builder.build(&config).unwrap();
        assert_eq!(plugin.name(), "cache");
    }

    #[test]
    fn test_build_forward_plugin() {
        let mut builder = PluginBuilder::new();
        let mut config_map = HashMap::new();

        let upstreams = vec![
            Value::String("udp://8.8.8.8:53".to_string()),
            Value::String("tcp://1.1.1.1:53".to_string()),
        ];
        config_map.insert("upstreams".to_string(), Value::Sequence(upstreams));

        let config = PluginConfig {
            tag: None,
            plugin_type: "forward".to_string(),
            args: Value::Mapping(Mapping::new()),
            priority: 100,
            config: config_map,
        };

        let plugin = builder.build(&config).unwrap();
        assert_eq!(plugin.name(), "forward");
    }

    #[test]
    fn test_build_forward_plugin_with_default_port() {
        let mut builder = PluginBuilder::new();
        let mut config_map = HashMap::new();

        let upstreams = vec![Value::String("udp://119.29.29.29".to_string())];
        config_map.insert("upstreams".to_string(), Value::Sequence(upstreams));

        let config = PluginConfig {
            tag: None,
            plugin_type: "forward".to_string(),
            args: Value::Mapping(Mapping::new()),
            priority: 100,
            config: config_map,
        };

        let plugin = builder.build(&config).unwrap();
        assert_eq!(plugin.name(), "forward");

        // Downcast to ForwardPlugin to inspect upstreams
        if let Some(fp) = plugin.as_ref().as_any().downcast_ref::<ForwardPlugin>() {
            let addrs = fp.upstream_addrs();
            assert_eq!(addrs.len(), 1);
            assert_eq!(addrs[0], "119.29.29.29:53");
        } else {
            panic!("Failed to downcast plugin to ForwardPlugin");
        }
    }

    #[test]
    fn test_parse_condition_qtype_single_and_multiple() {
        let builder = PluginBuilder::new();

        // Single type
        let cond = parse_condition(&builder, "qtype 1").unwrap();
        let mut req = Message::new();
        req.add_question(Question::new(
            "example.com".to_string(),
            RecordType::A,
            RecordClass::IN,
        ));
        let ctx = Context::new(req);
        assert!(cond(&ctx));

        // Multiple types
        let cond2 = parse_condition(&builder, "qtype 1 28").unwrap();
        let mut req2 = Message::new();
        req2.add_question(Question::new(
            "example.com".to_string(),
            RecordType::AAAA,
            RecordClass::IN,
        ));
        let ctx2 = Context::new(req2);
        assert!(cond2(&ctx2));
    }

    #[test]
    fn test_parse_sequence_steps_simple_exec() {
        let builder = PluginBuilder::new();

        // Test simple exec step
        let sequence = vec![Value::Mapping({
            let mut map = serde_yaml::Mapping::new();
            map.insert(
                Value::String("exec".to_string()),
                Value::String("accept".to_string()),
            );
            map
        })];

        let steps = parse_sequence_steps(&builder, &sequence).unwrap();
        assert_eq!(steps.len(), 1);

        match &steps[0] {
            crate::plugins::executable::SequenceStep::Exec(plugin) => {
                assert_eq!(plugin.name(), "accept");
            }
            _ => panic!("Expected Exec step"),
        }
    }

    #[test]
    fn test_parse_sequence_steps_conditional() {
        let builder = PluginBuilder::new();

        // Test conditional step
        let sequence = vec![Value::Mapping({
            let mut map = serde_yaml::Mapping::new();
            map.insert(
                Value::String("matches".to_string()),
                Value::String("has_resp".to_string()),
            );
            map.insert(
                Value::String("exec".to_string()),
                Value::String("accept".to_string()),
            );
            map
        })];

        let steps = parse_sequence_steps(&builder, &sequence).unwrap();
        assert_eq!(steps.len(), 1);

        match &steps[0] {
            crate::plugins::executable::SequenceStep::If {
                condition: _,
                action,
                desc,
            } => {
                assert_eq!(action.name(), "accept");
                assert_eq!(desc, "has_resp");
            }
            _ => panic!("Expected If step"),
        }
    }

    #[test]
    fn test_parse_sequence_steps_invalid() {
        let builder = PluginBuilder::new();

        // Test invalid sequence step (no exec or matches)
        let sequence = vec![Value::Mapping(serde_yaml::Mapping::new())];

        let result = parse_sequence_steps(&builder, &sequence);
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .to_string()
                .contains("sequence step must have exec or matches")
        );
    }

    #[test]
    fn test_parse_exec_action_plugin_reference() {
        let mut builder = PluginBuilder::new();

        // Add a plugin to reference
        let plugin: Arc<dyn Plugin> = Arc::new(crate::plugins::AcceptPlugin::new());
        builder
            .plugins
            .insert("test_plugin".to_string(), plugin.clone());

        // Test plugin reference
        let exec_value = Value::String("$test_plugin".to_string());
        let result = parse_exec_action(&builder, &exec_value).unwrap();
        assert_eq!(result.name(), "accept");
    }

    #[test]
    fn test_parse_exec_action_exec_plugin() {
        let builder = PluginBuilder::new();

        // Test exec plugin (accept)
        let exec_value = Value::String("accept".to_string());
        let result = parse_exec_action(&builder, &exec_value).unwrap();
        assert_eq!(result.name(), "accept");
    }

    #[test]
    fn test_parse_exec_action_unknown() {
        let builder = PluginBuilder::new();

        // Test unknown exec action
        let exec_value = Value::String("unknown_action".to_string());
        let result = parse_exec_action(&builder, &exec_value);
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .to_string()
                .contains("Unknown exec action")
        );
    }

    #[test]
    fn test_parse_exec_action_invalid_value_type() {
        let builder = PluginBuilder::new();

        // Test invalid value type (should be string)
        let exec_value = Value::Number(42.into());
        let result = parse_exec_action(&builder, &exec_value);
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .to_string()
                .contains("exec value must be string")
        );
    }

    #[test]
    fn test_derived_plugin_type_names() {
        // Ensure the macro-based derivation registers canonical names derived from type names
        crate::plugin::factory::init();
        let types = crate::plugin::factory::get_all_plugin_types();

        assert!(types.contains(&"query_acl".to_string()));
        assert!(types.contains(&"cache".to_string()));
        #[cfg(feature = "cron")]
        assert!(types.contains(&"cron".to_string()));
        assert!(types.contains(&"domain_validator".to_string()));
        assert!(types.contains(&"forward".to_string()));
        assert!(types.contains(&"geo_ip".to_string()));
        assert!(types.contains(&"geo_site".to_string()));
        assert!(types.contains(&"arbitrary".to_string()));
        assert!(types.contains(&"hosts".to_string()));
        assert!(types.contains(&"domain_set".to_string()));
        assert!(types.contains(&"ip_set".to_string()));

        assert!(types.contains(&"dual_selector".to_string()));
        assert!(types.contains(&"edns0_opt".to_string()));
        assert!(types.contains(&"rate_limit".to_string()));
        assert!(types.contains(&"redirect".to_string()));
        assert!(types.contains(&"reverse_lookup".to_string()));
        assert!(types.contains(&"ros_addrlist".to_string()));
        assert!(types.contains(&"blackhole".to_string()));

        let types = crate::plugin::factory::get_all_exec_plugin_types();

        assert!(types.contains(&"blackhole".to_string()));
        assert!(types.contains(&"debug_print".to_string()));
        assert!(types.contains(&"drop_resp".to_string()));
        assert!(types.contains(&"ecs".to_string()));
        assert!(types.contains(&"fallback".to_string()));
        assert!(types.contains(&"ipset".to_string()));
        assert!(types.contains(&"mark".to_string()));
        assert!(types.contains(&"nftset".to_string()));
        assert!(types.contains(&"query_summary".to_string()));
        assert!(types.contains(&"sleep".to_string()));
        assert!(types.contains(&"ttl".to_string()));
        assert!(types.contains(&"prefer_ipv4".to_string()));
        assert!(types.contains(&"prefer_ipv6".to_string()));
        #[cfg(feature = "metrics")]
        {
            assert!(types.contains(&"prom_metrics_collector".to_string()));
            assert!(types.contains(&"metrics_collector".to_string()));
        }
    }

    #[test]
    fn test_derived_plugin_name_mapping() {
        // Local helper that mirrors the macro's derivation algorithm
        fn derive<T: 'static>() -> String {
            let t = std::any::type_name::<T>();
            let last = t.rsplit("::").next().unwrap_or(t);
            let base = last.strip_suffix("Plugin").unwrap_or(last);
            let mut s = String::new();
            for (i, ch) in base.chars().enumerate() {
                if ch.is_uppercase() {
                    if i != 0 {
                        s.push('_');
                    }
                    for lc in ch.to_lowercase() {
                        s.push(lc);
                    }
                } else {
                    s.push(ch);
                }
            }
            s
        }

        assert_eq!(
            derive::<crate::plugins::executable::DropRespPlugin>(),
            "drop_resp"
        );
        assert_eq!(derive::<crate::plugins::ForwardPlugin>(), "forward");
        assert_eq!(derive::<crate::plugins::AcceptPlugin>(), "accept");
        assert_eq!(
            derive::<crate::plugins::flow::return_plugin::ReturnPlugin>(),
            "return"
        );
        assert_eq!(derive::<crate::plugins::flow::jump::JumpPlugin>(), "jump");
        assert_eq!(
            derive::<crate::plugins::flow::reject::RejectPlugin>(),
            "reject"
        );
        assert_eq!(
            derive::<crate::plugins::flow::prefer_ipv4::PreferIpv4Plugin>(),
            "prefer_ipv4"
        );
        assert_eq!(
            derive::<crate::plugins::flow::prefer_ipv6::PreferIpv6Plugin>(),
            "prefer_ipv6"
        );
        assert_eq!(derive::<crate::plugins::CachePlugin>(), "cache");
        assert_eq!(
            derive::<crate::plugins::dataset::DomainSetPlugin>(),
            "domain_set"
        );
    }

    #[test]
    fn test_no_derived_name_collisions() {
        fn derive<T: 'static>() -> String {
            let t = std::any::type_name::<T>();
            let last = t.rsplit("::").next().unwrap_or(t);
            let base = last.strip_suffix("Plugin").unwrap_or(last);
            let mut s = String::new();
            for (i, ch) in base.chars().enumerate() {
                if ch.is_uppercase() {
                    if i != 0 {
                        s.push('_');
                    }
                    for lc in ch.to_lowercase() {
                        s.push(lc);
                    }
                } else {
                    s.push(ch);
                }
            }
            s
        }

        // A representative set of plugin types to check for accidental collisions
        let derived = vec![
            derive::<crate::plugins::executable::DropRespPlugin>(),
            derive::<crate::plugins::ForwardPlugin>(),
            derive::<crate::plugins::AcceptPlugin>(),
            derive::<crate::plugins::flow::return_plugin::ReturnPlugin>(),
            derive::<crate::plugins::flow::jump::JumpPlugin>(),
            derive::<crate::plugins::flow::reject::RejectPlugin>(),
            derive::<crate::plugins::flow::prefer_ipv4::PreferIpv4Plugin>(),
            derive::<crate::plugins::flow::prefer_ipv6::PreferIpv6Plugin>(),
            derive::<crate::plugins::CachePlugin>(),
            derive::<crate::plugins::dataset::DomainSetPlugin>(),
            derive::<crate::plugins::geoip::GeoIpPlugin>(),
            derive::<crate::plugins::geosite::GeoSitePlugin>(),
            derive::<crate::plugins::HostsPlugin>(),
        ];

        let set: std::collections::HashSet<_> = derived.iter().cloned().collect();
        assert_eq!(
            set.len(),
            derived.len(),
            "Derived plugin names collided: {:?}",
            {
                // Build a list of duplicates for better diagnostics
                let mut counts = std::collections::HashMap::new();
                for name in &derived {
                    *counts.entry(name.clone()).or_insert(0usize) += 1;
                }
                counts
                    .into_iter()
                    .filter_map(|(k, v)| if v > 1 { Some(k) } else { None })
                    .collect::<Vec<_>>()
            }
        );
    }

    #[tokio::test]
    async fn test_build_redirect_from_string_rule_executes() {
        let mut builder = PluginBuilder::new();
        let mut args_map = Mapping::new();
        args_map.insert(
            Value::String("rules".to_string()),
            Value::Sequence(vec![Value::String("example.com example.net".to_string())]),
        );

        let config = PluginConfig {
            tag: Some("redirect_str".to_string()),
            plugin_type: "redirect".to_string(),
            args: Value::Mapping(args_map),
            priority: 100,
            config: HashMap::new(),
        };

        let plugin = builder.build(&config).expect("build redirect plugin");
        assert_eq!(plugin.name(), "redirect");

        // Execute plugin and verify it rewrites the qname
        let mut request = Message::new();
        request.add_question(Question::new(
            "example.com".to_string(),
            RecordType::A,
            RecordClass::IN,
        ));
        let mut ctx = Context::new(request);

        plugin.execute(&mut ctx).await.expect("execute");

        let got = ctx
            .request()
            .questions()
            .first()
            .unwrap()
            .qname()
            .to_string();
        assert_eq!(got, "example.net");
    }

    #[tokio::test]
    async fn test_build_redirect_from_mapping_rule_executes() {
        let mut builder = PluginBuilder::new();
        let mut args_map = Mapping::new();

        let mut rule_map = Mapping::new();
        rule_map.insert(
            Value::String("from".to_string()),
            Value::String("foo.example".to_string()),
        );
        rule_map.insert(
            Value::String("to".to_string()),
            Value::String("bar.example".to_string()),
        );

        args_map.insert(
            Value::String("rules".to_string()),
            Value::Sequence(vec![Value::Mapping(rule_map)]),
        );

        let config = PluginConfig {
            tag: Some("redirect_map".to_string()),
            plugin_type: "redirect".to_string(),
            args: Value::Mapping(args_map),
            priority: 100,
            config: HashMap::new(),
        };

        let plugin = builder.build(&config).expect("build redirect plugin");
        assert_eq!(plugin.name(), "redirect");

        // Execute plugin and verify it rewrites the qname
        let mut request = Message::new();
        request.add_question(Question::new(
            "foo.example".to_string(),
            RecordType::A,
            RecordClass::IN,
        ));
        let mut ctx = Context::new(request);

        plugin.execute(&mut ctx).await.expect("execute");

        let got = ctx
            .request()
            .questions()
            .first()
            .unwrap()
            .qname()
            .to_string();
        assert_eq!(got, "bar.example");
    }

    #[test]
    fn test_build_plugin_type_case_insensitive() {
        let mut builder = PluginBuilder::new();
        let mut args_map = Mapping::new();
        args_map.insert(
            Value::String("rules".to_string()),
            Value::Sequence(vec![Value::String("a b".to_string())]),
        );

        let config = PluginConfig {
            tag: Some("redirect_upper".to_string()),
            plugin_type: "Redirect".to_string(),
            args: Value::Mapping(args_map),
            priority: 100,
            config: HashMap::new(),
        };

        let plugin = builder.build(&config).expect("build redirect plugin");
        assert_eq!(plugin.name(), "redirect");
    }

    #[test]
    fn test_fallback_resolves_children() {
        let mut builder = PluginBuilder::new();
        // Insert primary and secondary helper plugins directly into the
        // builder registry. Some test environments do not auto-register
        // control-flow plugin factories, so creating and registering the
        // helper plugins manually ensures fallback resolution can proceed.
        let primary_plugin = Arc::new(crate::plugins::flow::AcceptPlugin::new());
        builder
            .plugins
            .insert("primary".to_string(), primary_plugin);
        let secondary_plugin = Arc::new(crate::plugins::flow::AcceptPlugin::new());
        builder
            .plugins
            .insert("secondary".to_string(), secondary_plugin);

        // Create plugin configs for primary/secondary (used by resolve_references)
        let primary_cfg = PluginConfig {
            tag: None,
            plugin_type: "accept".to_string(),
            args: Value::Mapping(Mapping::new()),
            priority: 100,
            config: HashMap::new(),
        };
        let secondary_cfg = PluginConfig {
            tag: None,
            plugin_type: "accept".to_string(),
            args: Value::Mapping(Mapping::new()),
            priority: 100,
            config: HashMap::new(),
        };

        // Create fallback config referencing the above by name
        let mut args_map = Mapping::new();
        args_map.insert(
            Value::String("primary".to_string()),
            Value::String("primary".to_string()),
        );
        args_map.insert(
            Value::String("secondary".to_string()),
            Value::String("secondary".to_string()),
        );

        let fb_cfg = PluginConfig {
            tag: None,
            plugin_type: "fallback".to_string(),
            args: Value::Mapping(args_map),
            priority: 100,
            config: HashMap::new(),
        };

        builder.build(&fb_cfg).unwrap();

        // Resolve references
        builder
            .resolve_references(&[primary_cfg, secondary_cfg, fb_cfg])
            .unwrap();

        // Verify fallback has resolved children
        let plugin = builder
            .get_plugin("fallback")
            .expect("fallback plugin present");
        if let Some(fp) = plugin
            .as_ref()
            .as_any()
            .downcast_ref::<crate::plugins::executable::FallbackPlugin>()
        {
            assert_eq!(fp.resolved_child_count(), 2);
            assert_eq!(fp.pending_child_count(), 0);
        } else {
            panic!("fallback plugin is wrong type");
        }
    }

    #[test]
    fn test_parse_condition_has_resp() {
        let builder = PluginBuilder::new();

        let condition = parse_condition(&builder, "has_resp").unwrap();

        // Test with no response
        let ctx = Context::new(Message::new());
        assert!(!condition(&ctx));

        // Test with response
        let mut ctx_with_resp = Context::new(Message::new());
        ctx_with_resp.set_response(Some(Message::new()));
        assert!(condition(&ctx_with_resp));
    }

    #[test]
    fn test_parse_condition_resp_ip() {
        let mut builder = PluginBuilder::new();

        // Create and register an IP set plugin
        let ip_set_plugin = Arc::new(crate::plugins::dataset::IpSetPlugin::new("test_ip_set"));
        builder
            .plugins
            .insert("test_ip_set".to_string(), ip_set_plugin);

        let condition = parse_condition(&builder, "resp_ip $test_ip_set").unwrap();

        // Test with context that has response
        let mut ctx = Context::new(Message::new());
        ctx.set_response(Some(Message::new()));

        // The condition should not panic and should return false for non-matching context
        // (since our test IP set is empty)
        assert!(!condition(&ctx));
    }

    #[test]
    fn test_parse_condition_negated_resp_ip() {
        let mut builder = PluginBuilder::new();

        // Create and register an IP set plugin
        let ip_set_plugin = Arc::new(crate::plugins::dataset::IpSetPlugin::new("test_ip_set"));
        builder
            .plugins
            .insert("test_ip_set".to_string(), ip_set_plugin);

        let condition = parse_condition(&builder, "!resp_ip $test_ip_set").unwrap();

        let mut ctx = Context::new(Message::new());
        ctx.set_response(Some(Message::new()));

        // Should return true for non-matching (negated)
        assert!(condition(&ctx));
    }

    #[test]
    fn test_parse_condition_qname() {
        let mut builder = PluginBuilder::new();

        // Create and register a domain set plugin
        let domain_set_plugin = Arc::new(crate::plugins::dataset::DomainSetPlugin::new(
            "test_domain_set",
        ));
        builder
            .plugins
            .insert("test_domain_set".to_string(), domain_set_plugin);

        let condition = parse_condition(&builder, "qname $test_domain_set").unwrap();

        // Test with a query
        let mut req = Message::new();
        req.add_question(Question::new(
            "example.com".to_string(),
            RecordType::A,
            RecordClass::IN,
        ));
        let ctx = Context::new(req);

        // Should return false for non-matching (empty domain set)
        assert!(!condition(&ctx));
    }

    #[test]
    fn test_parse_condition_negated_qname() {
        let builder = PluginBuilder::new();

        let condition = parse_condition(&builder, "!qname example.com").unwrap();

        // Test with matching domain (should return false due to negation)
        let mut req = Message::new();
        req.add_question(Question::new(
            "example.com".to_string(),
            RecordType::A,
            RecordClass::IN,
        ));
        let ctx = Context::new(req);
        assert!(!condition(&ctx));

        // Test with non-matching domain (should return true due to negation)
        let mut req2 = Message::new();
        req2.add_question(Question::new(
            "other.com".to_string(),
            RecordType::A,
            RecordClass::IN,
        ));
        let ctx2 = Context::new(req2);
        assert!(condition(&ctx2));
    }

    #[test]
    fn test_parse_condition_qtype_invalid() {
        let builder = PluginBuilder::new();

        assert!(parse_condition(&builder, "qtype").is_err());
        assert!(parse_condition(&builder, "qtype abc").is_err());
        assert!(parse_condition(&builder, "qtype 1 abc").is_err());
    }

    #[test]
    fn test_parse_condition_qclass() {
        let builder = PluginBuilder::new();

        // Test qclass with name
        let condition = parse_condition(&builder, "qclass IN").unwrap();
        let mut request = Message::new();
        request.add_question(Question::new(
            "example.com".to_string(),
            RecordType::A,
            RecordClass::IN,
        ));
        let ctx = Context::new(request);
        assert!(condition(&ctx));

        // Test qclass with different class
        let mut request = Message::new();
        request.add_question(Question::new(
            "example.com".to_string(),
            RecordType::A,
            RecordClass::CH,
        ));
        let ctx = Context::new(request);
        let condition = parse_condition(&builder, "qclass IN").unwrap();
        assert!(!condition(&ctx));

        // Test qclass with multiple values
        let condition = parse_condition(&builder, "qclass IN CH").unwrap();
        let mut request = Message::new();
        request.add_question(Question::new(
            "example.com".to_string(),
            RecordType::A,
            RecordClass::CH,
        ));
        let ctx = Context::new(request);
        assert!(condition(&ctx));

        // Test numeric class
        let condition = parse_condition(&builder, "qclass 1").unwrap();
        let mut request = Message::new();
        request.add_question(Question::new(
            "example.com".to_string(),
            RecordType::A,
            RecordClass::IN,
        ));
        let ctx = Context::new(request);
        assert!(condition(&ctx));
    }

    #[test]
    fn test_parse_condition_rcode() {
        let builder = PluginBuilder::new();

        // Test rcode with NoError
        let condition = parse_condition(&builder, "rcode NOERROR").unwrap();
        let mut response = Message::new();
        response.set_response_code(ResponseCode::NoError);
        let mut ctx = Context::new(Message::new());
        ctx.set_response(Some(response));
        assert!(condition(&ctx));

        // Test rcode with NXDomain
        let condition = parse_condition(&builder, "rcode NXDOMAIN").unwrap();
        let mut response = Message::new();
        response.set_response_code(ResponseCode::NXDomain);
        let mut ctx = Context::new(Message::new());
        ctx.set_response(Some(response));
        assert!(condition(&ctx));

        // Test rcode with multiple values
        let condition = parse_condition(&builder, "rcode NOERROR NXDOMAIN").unwrap();
        let mut response = Message::new();
        response.set_response_code(ResponseCode::NXDomain);
        let mut ctx = Context::new(Message::new());
        ctx.set_response(Some(response));
        assert!(condition(&ctx));

        // Test rcode mismatch
        let condition = parse_condition(&builder, "rcode NOERROR").unwrap();
        let mut response = Message::new();
        response.set_response_code(ResponseCode::ServFail);
        let mut ctx = Context::new(Message::new());
        ctx.set_response(Some(response));
        assert!(!condition(&ctx));

        // Test numeric rcode
        let condition = parse_condition(&builder, "rcode 3").unwrap();
        let mut response = Message::new();
        response.set_response_code(ResponseCode::NXDomain);
        let mut ctx = Context::new(Message::new());
        ctx.set_response(Some(response));
        assert!(condition(&ctx));
    }

    #[test]
    fn test_parse_condition_has_cname() {
        let builder = PluginBuilder::new();

        // Test with CNAME present
        let condition = parse_condition(&builder, "has_cname").unwrap();
        let mut response = Message::new();
        response.add_answer(ResourceRecord::new(
            "example.com".to_string(),
            RecordType::CNAME,
            RecordClass::IN,
            300,
            RData::CNAME("target.example.com".to_string()),
        ));
        let mut ctx = Context::new(Message::new());
        ctx.set_response(Some(response));
        assert!(condition(&ctx));

        // Test without CNAME
        let condition = parse_condition(&builder, "has_cname").unwrap();
        let mut response = Message::new();
        response.add_answer(ResourceRecord::new(
            "example.com".to_string(),
            RecordType::A,
            RecordClass::IN,
            300,
            RData::A("192.168.1.1".parse().unwrap()),
        ));
        let mut ctx = Context::new(Message::new());
        ctx.set_response(Some(response));
        assert!(!condition(&ctx));

        // Test without response
        let condition = parse_condition(&builder, "has_cname").unwrap();
        let ctx = Context::new(Message::new());
        assert!(!condition(&ctx));
    }

    #[test]
    fn test_parse_condition_qclass_invalid() {
        let builder = PluginBuilder::new();

        // Test invalid class name
        let result = parse_condition(&builder, "qclass INVALID");
        assert!(result.is_err());

        // Test empty qclass
        let result = parse_condition(&builder, "qclass");
        assert!(result.is_err());
    }

    #[test]
    fn test_parse_condition_rcode_invalid() {
        let builder = PluginBuilder::new();

        // Test invalid rcode name
        let result = parse_condition(&builder, "rcode INVALID");
        assert!(result.is_err());

        // Test empty rcode
        let result = parse_condition(&builder, "rcode");
        assert!(result.is_err());
    }

    #[test]
    fn test_parse_condition_unknown() {
        let builder = PluginBuilder::new();

        let result = parse_condition(&builder, "unknown_condition");
        assert!(result.is_err());
        // We can't easily check the error message due to trait bounds,
        // but we can verify it's an error
    }
}