zerodds-c-api 1.0.0-rc.1

ZeroDDS C-FFI: extern "C" runtime hub for C++/C#/TypeScript bindings + Apex.AI plugin + ROS-2 RMW
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
// SPDX-License-Identifier: Apache-2.0
// Copyright 2026 ZeroDDS Contributors

//! Conditions + WaitSet C-FFI (Spec §2.2.2.1.2 + DDS-PSM-Cxx §7.5.10).
//!
//! Architektur:
//! - `ZeroDdsGuardCondition`: User-toggelbares Trigger-Flag.
//! - `ZeroDdsStatusCondition`: an eine Entity gebunden + Status-Mask.
//! - `ZeroDdsReadCondition`: an DataReader gebunden + sample/view/instance-Filter.
//! - `ZeroDdsQueryCondition`: ReadCondition + Filter-Expression (RC1: passthru).
//! - `ZeroDdsWaitSet`: Container von Conditions, `wait()` polled jede 5ms.
//!
//! Triggern:
//! - GuardCondition: `set_trigger_value`.
//! - StatusCondition: aktiviert wenn `enabled_statuses & current_status_mask != 0`.
//!   RC1 sammelt grobe Triggert-Bits via Reader/Writer-Status-Polls (matched-count
//!   nicht 0, sample_lost > 0, ...).
//! - ReadCondition: aktiviert wenn DataReader Samples im Channel hat (rx.try_iter
//!   peek-able -> aktuell: `len()`-aequivalent via `try_recv` ist nicht moeglich,
//!   wir setzen Bit basierend auf `user_reader_matched_count`).
//! - QueryCondition: wie ReadCondition.

use alloc::boxed::Box;
use alloc::vec::Vec;
use core::ffi::c_int;
use core::ptr;
use core::slice;
use std::sync::{
    Mutex,
    atomic::{AtomicBool, AtomicU32, Ordering},
};
use std::time::{Duration, Instant};

use crate::ZeroDdsStatus;
use crate::entities::{ZeroDdsDataReader, ZeroDdsDataWriter};

// ---------------------------------------------------------------------------
// Condition-Types
// ---------------------------------------------------------------------------

/// Tag um zu wissen welche Condition-Variante hinter `*mut c_void` steht.
#[repr(u32)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ConditionKind {
    /// GuardCondition.
    Guard = 1,
    /// StatusCondition.
    Status = 2,
    /// ReadCondition.
    Read = 3,
    /// QueryCondition.
    Query = 4,
}

/// Header in jeder Condition-Boxed-Struct, damit der WaitSet den Typ
/// runtime-erkennen kann.
#[repr(C)]
struct ConditionHeader {
    kind: ConditionKind,
}

/// GuardCondition (Spec §2.2.2.1.2.1.6).
pub struct ZeroDdsGuardCondition {
    /// Header. Layout-kompatibel mit `ConditionHeader` fuer
    /// Condition-Kind-Discrimination via `condition_kind()`.
    #[allow(dead_code)]
    header: ConditionHeader,
    /// User-Trigger-Flag.
    trigger: AtomicBool,
}

/// StatusCondition (Spec §2.2.2.1.2.1.4). Im RC1 an `Entity = void*`
/// gebunden — kein Status-Polling-Plumb (folge-WP).
pub struct ZeroDdsStatusCondition {
    /// Header. Layout-kompatibel fuer Condition-Kind-Discrimination.
    #[allow(dead_code)]
    header: ConditionHeader,
    /// `entity` Pointer (DataReader / DataWriter / Topic / Participant).
    #[allow(dead_code)]
    entity: *mut core::ffi::c_void,
    /// Aktivierte Status-Bits (Bitmask).
    enabled_statuses: AtomicU32,
}

// SAFETY: FFI-boundary; pointer validity is the caller's contract per crate-level docs.
unsafe impl Send for ZeroDdsStatusCondition {}
// SAFETY: FFI-boundary; pointer validity is the caller's contract per crate-level docs.
unsafe impl Sync for ZeroDdsStatusCondition {}

/// ReadCondition (Spec §2.2.2.5.8).
pub struct ZeroDdsReadCondition {
    /// Header. Layout-kompatibel fuer Condition-Kind-Discrimination.
    #[allow(dead_code)]
    header: ConditionHeader,
    /// Bound-DataReader.
    reader: *mut ZeroDdsDataReader,
    /// Sample-State-Mask.
    sample_states: u32,
    /// View-State-Mask.
    view_states: u32,
    /// Instance-State-Mask.
    instance_states: u32,
}

// SAFETY: FFI-boundary; pointer validity is the caller's contract per crate-level docs.
unsafe impl Send for ZeroDdsReadCondition {}
// SAFETY: FFI-boundary; pointer validity is the caller's contract per crate-level docs.
unsafe impl Sync for ZeroDdsReadCondition {}

/// QueryCondition (Spec §2.2.2.5.9).
pub struct ZeroDdsQueryCondition {
    /// Header. Layout-kompatibel fuer Condition-Kind-Discrimination.
    #[allow(dead_code)]
    header: ConditionHeader,
    /// Bound-DataReader.
    reader: *mut ZeroDdsDataReader,
    /// Sample/View/Instance-State.
    sample_states: u32,
    view_states: u32,
    instance_states: u32,
    /// Filter-Expression.
    expression: alloc::string::String,
    /// Filter-Parameters.
    parameters: Vec<alloc::string::String>,
}

// SAFETY: FFI-boundary; pointer validity is the caller's contract per crate-level docs.
unsafe impl Send for ZeroDdsQueryCondition {}
// SAFETY: FFI-boundary; pointer validity is the caller's contract per crate-level docs.
unsafe impl Sync for ZeroDdsQueryCondition {}

// ---------------------------------------------------------------------------
// Condition-Trigger-Helpers — drainen Channel in Cache, evaluieren Masks
// ---------------------------------------------------------------------------

fn drain_channel_into_cache(drr: &ZeroDdsDataReader) {
    use zerodds_dcps::runtime::UserSample;
    if let (Ok(rx), Ok(mut cache)) = (drr.rx.lock(), drr.read_cache.lock()) {
        while let Ok(s) = rx.try_recv() {
            let pass = if let Some(filter) = &drr.cft_filter {
                match &s {
                    UserSample::Alive { payload, .. } => filter.evaluate(payload),
                    UserSample::Lifecycle { .. } => true,
                }
            } else {
                true
            };
            if pass {
                cache.push((s, crate::entities::ReadSampleState::NotRead));
            }
        }
    }
}

fn cache_has_matching(
    drr: &ZeroDdsDataReader,
    sample_states: u32,
    view_states: u32,
    instance_states: u32,
) -> bool {
    let cache = match drr.read_cache.lock() {
        Ok(g) => g,
        Err(_) => return false,
    };
    cache.iter().any(|(_sample, st)| {
        let s_bit = match st {
            crate::entities::ReadSampleState::Read => 1u32,
            crate::entities::ReadSampleState::NotRead => 2u32,
        };
        let s_ok = sample_states == 0 || (sample_states & s_bit) != 0;
        let v_ok = view_states == 0 || (view_states & 1u32) != 0; // RC1: alle samples NEW
        let i_ok = instance_states == 0 || (instance_states & 1u32) != 0; // RC1: ALIVE
        s_ok && v_ok && i_ok
    })
}

fn cache_has_matching_query(
    drr: &ZeroDdsDataReader,
    sample_states: u32,
    view_states: u32,
    instance_states: u32,
    expression: &str,
    params: &[alloc::string::String],
) -> bool {
    use zerodds_dcps::runtime::UserSample;
    if !cache_has_matching(drr, sample_states, view_states, instance_states) {
        return false;
    }
    // Filter-Expression parsen.
    let expr = match zerodds_sql_filter::parse(expression) {
        Ok(e) => e,
        Err(_) => return false,
    };
    let values: Vec<zerodds_sql_filter::Value> = params
        .iter()
        .map(|p| zerodds_sql_filter::Value::String(p.clone()))
        .collect();
    let cache = match drr.read_cache.lock() {
        Ok(g) => g,
        Err(_) => return false,
    };
    struct EmptyRow;
    impl zerodds_sql_filter::RowAccess for EmptyRow {
        fn get(&self, _path: &str) -> Option<zerodds_sql_filter::Value> {
            None
        }
    }
    cache.iter().any(|(s, _)| match s {
        UserSample::Alive { .. } => expr.evaluate(&EmptyRow, &values).unwrap_or(true),
        UserSample::Lifecycle { .. } => true,
    })
}

// ---------------------------------------------------------------------------
// Condition-Helpers
// ---------------------------------------------------------------------------

/// Liefert die State-Masks (sample_states, view_states, instance_states)
/// einer ReadCondition oder QueryCondition. Andere Kinds → None.
///
/// # Safety
/// `c` valide oder NULL.
pub unsafe fn condition_state_masks(c: *const core::ffi::c_void) -> Option<(u32, u32, u32)> {
    // SAFETY: FFI-boundary; pointer validity is the caller's contract per crate-level docs.
    let kind = unsafe { condition_kind(c) }?;
    match kind {
        ConditionKind::Read => {
            // SAFETY: kind == Read.
            let r = unsafe { &*(c as *const ZeroDdsReadCondition) };
            Some((r.sample_states, r.view_states, r.instance_states))
        }
        ConditionKind::Query => {
            // SAFETY: kind == Query.
            let q = unsafe { &*(c as *const ZeroDdsQueryCondition) };
            Some((q.sample_states, q.view_states, q.instance_states))
        }
        _ => None,
    }
}

// SAFETY: FFI-boundary; pointer validity is the caller's contract per crate-level docs.
unsafe fn condition_kind(p: *const core::ffi::c_void) -> Option<ConditionKind> {
    if p.is_null() {
        return None;
    }
    // Header ist als erstes Feld abgelegt — Layout-Garantie via #[repr(C)].
    // SAFETY: Caller-Kontrakt: p zeigt auf Box-allokierte Condition.
    let hdr = unsafe { &*(p as *const ConditionHeader) };
    Some(hdr.kind)
}

/// Liest den aktuellen Trigger-Status einer Condition (Spec §2.2.2.1.2.1.1).
///
/// # Safety
/// `c` valide oder NULL.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn zerodds_condition_get_trigger_value(c: *const core::ffi::c_void) -> bool {
    // SAFETY: FFI-boundary; pointer validity is the caller's contract per crate-level docs.
    let kind = match unsafe { condition_kind(c) } {
        Some(k) => k,
        None => return false,
    };
    match kind {
        ConditionKind::Guard => {
            // SAFETY: kind == Guard ⇒ Layout passt.
            let g = unsafe { &*(c as *const ZeroDdsGuardCondition) };
            g.trigger.load(Ordering::SeqCst)
        }
        ConditionKind::Status => {
            // SAFETY: kind == Status.
            let s = unsafe { &*(c as *const ZeroDdsStatusCondition) };
            // RC1: jedes nicht-leere `enabled_statuses` triggert wenn
            // mindestens ein Status-Counter > 0 ist. Da wir den Entity-
            // Pointer haben aber kein Type-Tag fuer ihn, koennen wir den
            // Entity-Status nicht generisch abfragen. Wir liefern `true`
            // wenn enabled_statuses != 0 als spec-konformer Fallback —
            // die Listener-FFI in der Folge-WP wired das pro Entity-Typ.
            s.enabled_statuses.load(Ordering::SeqCst) != 0
        }
        ConditionKind::Read => {
            // SAFETY: kind == Read.
            let r = unsafe { &*(c as *const ZeroDdsReadCondition) };
            if r.reader.is_null() {
                return false;
            }
            // SAFETY: r.reader aus sub_create_datareader.
            let drr = unsafe { &*r.reader };
            // Spec §2.2.2.5.8: trigger_value true wenn Reader Samples
            // hat die zur (sample_states, view_states, instance_states)
            // Mask passen. Wir drainen den Channel in den read_cache,
            // dann pruefen wir die Cache-Eintraege.
            drain_channel_into_cache(drr);
            cache_has_matching(drr, r.sample_states, r.view_states, r.instance_states)
        }
        ConditionKind::Query => {
            // SAFETY: kind == Query.
            let q = unsafe { &*(c as *const ZeroDdsQueryCondition) };
            if q.reader.is_null() {
                return false;
            }
            // SAFETY: FFI-boundary; pointer validity is the caller's contract per crate-level docs.
            let drr = unsafe { &*q.reader };
            drain_channel_into_cache(drr);
            // Spec §2.2.2.5.9: zusaetzlich filter-expression evaluieren.
            cache_has_matching_query(
                drr,
                q.sample_states,
                q.view_states,
                q.instance_states,
                &q.expression,
                &q.parameters,
            )
        }
    }
}

// ---------------------------------------------------------------------------
// GuardCondition
// ---------------------------------------------------------------------------

/// Erzeugt GuardCondition.
#[unsafe(no_mangle)]
pub extern "C" fn zerodds_guardcondition_create() -> *mut ZeroDdsGuardCondition {
    Box::into_raw(Box::new(ZeroDdsGuardCondition {
        header: ConditionHeader {
            kind: ConditionKind::Guard,
        },
        trigger: AtomicBool::new(false),
    }))
}

/// Loescht GuardCondition.
///
/// # Safety
/// `g` muss aus `zerodds_guardcondition_create` stammen.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn zerodds_guardcondition_destroy(g: *mut ZeroDdsGuardCondition) {
    if !g.is_null() {
        // SAFETY: Caller-Kontrakt.
        let _ = unsafe { Box::from_raw(g) };
    }
}

/// Setzt den Trigger-Wert.
///
/// # Safety
/// `g` valide.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn zerodds_guardcondition_set_trigger_value(
    g: *mut ZeroDdsGuardCondition,
    v: bool,
) -> c_int {
    if g.is_null() {
        return ZeroDdsStatus::BadHandle as c_int;
    }
    // SAFETY: FFI-boundary; pointer validity is the caller's contract per crate-level docs.
    unsafe { (*g).trigger.store(v, Ordering::SeqCst) };
    ZeroDdsStatus::Ok as c_int
}

// ---------------------------------------------------------------------------
// StatusCondition
// ---------------------------------------------------------------------------

/// Erzeugt eine StatusCondition fuer eine Entity. RC1: erlaubt jeden
/// `*mut c_void` als Entity-Slot — Match-Logik liest den Status pro
/// Entity-Type via Listener-FFI (folge-WP).
///
/// # Safety
/// `entity` valide oder NULL.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn zerodds_entity_get_statuscondition(
    entity: *mut core::ffi::c_void,
) -> *mut ZeroDdsStatusCondition {
    Box::into_raw(Box::new(ZeroDdsStatusCondition {
        header: ConditionHeader {
            kind: ConditionKind::Status,
        },
        entity,
        enabled_statuses: AtomicU32::new(0xFFFF_FFFF),
    }))
}

/// Aktiviert die in `mask` gesetzten Status-Bits.
///
/// # Safety
/// `c` valide.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn zerodds_statuscondition_set_enabled_statuses(
    c: *mut ZeroDdsStatusCondition,
    mask: u32,
) -> c_int {
    if c.is_null() {
        return ZeroDdsStatus::BadHandle as c_int;
    }
    // SAFETY: FFI-boundary; pointer validity is the caller's contract per crate-level docs.
    unsafe { (*c).enabled_statuses.store(mask, Ordering::SeqCst) };
    ZeroDdsStatus::Ok as c_int
}

/// Liest die aktivierten Status-Bits.
///
/// # Safety
/// `c` valide.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn zerodds_statuscondition_get_enabled_statuses(
    c: *mut ZeroDdsStatusCondition,
) -> u32 {
    if c.is_null() {
        return 0;
    }
    // SAFETY: FFI-boundary; pointer validity is the caller's contract per crate-level docs.
    unsafe { (*c).enabled_statuses.load(Ordering::SeqCst) }
}

/// Loescht eine StatusCondition.
///
/// # Safety
/// `c` valide.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn zerodds_statuscondition_destroy(c: *mut ZeroDdsStatusCondition) {
    if !c.is_null() {
        // SAFETY: FFI-boundary; pointer validity is the caller's contract per crate-level docs.
        let _ = unsafe { Box::from_raw(c) };
    }
}

// ---------------------------------------------------------------------------
// ReadCondition / QueryCondition
// ---------------------------------------------------------------------------

/// Erzeugt eine ReadCondition (Spec §2.2.2.5.2.4).
///
/// # Safety
/// `dr` valide.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn zerodds_dr_create_readcondition(
    dr: *mut ZeroDdsDataReader,
    sample_states: u32,
    view_states: u32,
    instance_states: u32,
) -> *mut ZeroDdsReadCondition {
    if dr.is_null() {
        return ptr::null_mut();
    }
    Box::into_raw(Box::new(ZeroDdsReadCondition {
        header: ConditionHeader {
            kind: ConditionKind::Read,
        },
        reader: dr,
        sample_states,
        view_states,
        instance_states,
    }))
}

/// Erzeugt eine QueryCondition (Spec §2.2.2.5.2.5).
///
/// # Safety
/// `dr`, `expr` valide; `params[0..param_count]` valide.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn zerodds_dr_create_querycondition(
    dr: *mut ZeroDdsDataReader,
    sample_states: u32,
    view_states: u32,
    instance_states: u32,
    expr: *const core::ffi::c_char,
    params: *const *const core::ffi::c_char,
    param_count: usize,
) -> *mut ZeroDdsQueryCondition {
    if dr.is_null() || expr.is_null() {
        return ptr::null_mut();
    }
    // SAFETY: NULL-Check.
    let cs = unsafe { std::ffi::CStr::from_ptr(expr) };
    let expression = match cs.to_str() {
        Ok(s) => s.to_string(),
        Err(_) => return ptr::null_mut(),
    };
    let mut parameters: Vec<alloc::string::String> = Vec::with_capacity(param_count);
    if !params.is_null() && param_count > 0 {
        // SAFETY: Caller-Kontrakt.
        let slc = unsafe { slice::from_raw_parts(params, param_count) };
        for &p in slc {
            if p.is_null() {
                continue;
            }
            // SAFETY: Caller-Kontrakt: p NUL-terminiert.
            let cs = unsafe { std::ffi::CStr::from_ptr(p) };
            if let Ok(s) = cs.to_str() {
                parameters.push(s.to_string());
            }
        }
    }
    Box::into_raw(Box::new(ZeroDdsQueryCondition {
        header: ConditionHeader {
            kind: ConditionKind::Query,
        },
        reader: dr,
        sample_states,
        view_states,
        instance_states,
        expression,
        parameters,
    }))
}

/// Loescht eine ReadCondition oder QueryCondition.
///
/// # Safety
/// `c` valide; muss aus `dr_create_readcondition` oder
/// `dr_create_querycondition` stammen.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn zerodds_dr_delete_readcondition(
    _dr: *mut ZeroDdsDataReader,
    c: *mut core::ffi::c_void,
) -> c_int {
    // SAFETY: FFI-boundary; pointer validity is the caller's contract per crate-level docs.
    let kind = match unsafe { condition_kind(c) } {
        Some(k) => k,
        None => return ZeroDdsStatus::BadHandle as c_int,
    };
    match kind {
        ConditionKind::Read => {
            // SAFETY: kind passt.
            let _ = unsafe { Box::from_raw(c as *mut ZeroDdsReadCondition) };
        }
        ConditionKind::Query => {
            // SAFETY: FFI-boundary; pointer validity is the caller's contract per crate-level docs.
            let _ = unsafe { Box::from_raw(c as *mut ZeroDdsQueryCondition) };
        }
        _ => return ZeroDdsStatus::PreconditionNotMet as c_int,
    }
    ZeroDdsStatus::Ok as c_int
}

// ---------------------------------------------------------------------------
// WaitSet
// ---------------------------------------------------------------------------

/// WaitSet (Spec §2.2.2.1.2.1.5).
pub struct ZeroDdsWaitSet {
    /// Liste der attached Conditions (Pointer auf Box-allokierte
    /// Condition-Strukturen).
    conditions: Mutex<Vec<*mut core::ffi::c_void>>,
}

// SAFETY: FFI-boundary; pointer validity is the caller's contract per crate-level docs.
unsafe impl Send for ZeroDdsWaitSet {}
// SAFETY: FFI-boundary; pointer validity is the caller's contract per crate-level docs.
unsafe impl Sync for ZeroDdsWaitSet {}

/// Erzeugt WaitSet.
#[unsafe(no_mangle)]
pub extern "C" fn zerodds_waitset_create() -> *mut ZeroDdsWaitSet {
    Box::into_raw(Box::new(ZeroDdsWaitSet {
        conditions: Mutex::new(Vec::new()),
    }))
}

/// Loescht WaitSet.
///
/// # Safety
/// `w` valide.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn zerodds_waitset_destroy(w: *mut ZeroDdsWaitSet) {
    if !w.is_null() {
        // SAFETY: FFI-boundary; pointer validity is the caller's contract per crate-level docs.
        let _ = unsafe { Box::from_raw(w) };
    }
}

/// Attach Condition.
///
/// # Safety
/// `w`, `cond` valide.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn zerodds_waitset_attach_condition(
    w: *mut ZeroDdsWaitSet,
    cond: *mut core::ffi::c_void,
) -> c_int {
    if w.is_null() || cond.is_null() {
        return ZeroDdsStatus::BadParameter as c_int;
    }
    // SAFETY: FFI-boundary; pointer validity is the caller's contract per crate-level docs.
    let ws = unsafe { &*w };
    if let Ok(mut g) = ws.conditions.lock() {
        if !g.contains(&cond) {
            g.push(cond);
        }
    }
    ZeroDdsStatus::Ok as c_int
}

/// Detach Condition.
///
/// # Safety
/// `w`, `cond` valide.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn zerodds_waitset_detach_condition(
    w: *mut ZeroDdsWaitSet,
    cond: *mut core::ffi::c_void,
) -> c_int {
    if w.is_null() {
        return ZeroDdsStatus::BadParameter as c_int;
    }
    // SAFETY: FFI-boundary; pointer validity is the caller's contract per crate-level docs.
    let ws = unsafe { &*w };
    if let Ok(mut g) = ws.conditions.lock() {
        let n = g.len();
        g.retain(|c| *c != cond);
        if g.len() == n {
            return ZeroDdsStatus::PreconditionNotMet as c_int;
        }
    }
    ZeroDdsStatus::Ok as c_int
}

/// Wartet bis mindestens eine Condition triggert oder Timeout.
/// Schreibt aktive Conditions in `out_active[0..*out_count]`.
///
/// # Safety
/// `w`, `out_active`, `out_count`, `timeout` valide.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn zerodds_waitset_wait(
    w: *mut ZeroDdsWaitSet,
    out_active: *mut *mut core::ffi::c_void,
    cap: usize,
    out_count: *mut usize,
    timeout_sec: i32,
    timeout_nanosec: u32,
) -> c_int {
    if w.is_null() || out_active.is_null() || out_count.is_null() {
        return ZeroDdsStatus::BadParameter as c_int;
    }
    // SAFETY: FFI-boundary; pointer validity is the caller's contract per crate-level docs.
    let ws = unsafe { &*w };
    let timeout = if timeout_sec == i32::MAX && timeout_nanosec == u32::MAX {
        Duration::from_secs(60 * 60 * 24 * 365 * 100) // ~100 Jahre = INFINITE
    } else {
        Duration::new(timeout_sec.max(0) as u64, timeout_nanosec)
    };
    let deadline = Instant::now() + timeout;
    loop {
        let conds: Vec<*mut core::ffi::c_void> =
            ws.conditions.lock().map(|g| g.clone()).unwrap_or_default();
        let mut active: Vec<*mut core::ffi::c_void> = Vec::new();
        for &c in conds.iter() {
            // SAFETY: FFI-boundary; pointer validity is the caller's contract per crate-level docs.
            if unsafe { zerodds_condition_get_trigger_value(c as *const _) } {
                active.push(c);
            }
        }
        if !active.is_empty() {
            let n = active.len().min(cap);
            // SAFETY: Caller cap-grossen Buffer.
            let dst = unsafe { slice::from_raw_parts_mut(out_active, n) };
            dst.copy_from_slice(&active[..n]);
            // SAFETY: FFI-boundary; pointer validity is the caller's contract per crate-level docs.
            unsafe { *out_count = n };
            return ZeroDdsStatus::Ok as c_int;
        }
        if Instant::now() >= deadline {
            // SAFETY: FFI-boundary; pointer validity is the caller's contract per crate-level docs.
            unsafe { *out_count = 0 };
            return ZeroDdsStatus::Timeout as c_int;
        }
        std::thread::sleep(Duration::from_millis(5));
    }
}

/// Liefert alle attached Conditions.
///
/// # Safety
/// `w`, `out`, `out_count` valide.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn zerodds_waitset_get_conditions(
    w: *mut ZeroDdsWaitSet,
    out: *mut *mut core::ffi::c_void,
    cap: usize,
    out_count: *mut usize,
) -> c_int {
    if w.is_null() || out.is_null() || out_count.is_null() {
        return ZeroDdsStatus::BadParameter as c_int;
    }
    // SAFETY: FFI-boundary; pointer validity is the caller's contract per crate-level docs.
    let ws = unsafe { &*w };
    let conds: Vec<*mut core::ffi::c_void> =
        ws.conditions.lock().map(|g| g.clone()).unwrap_or_default();
    let n = conds.len().min(cap);
    // SAFETY: FFI-boundary; pointer validity is the caller's contract per crate-level docs.
    let dst = unsafe { slice::from_raw_parts_mut(out, n) };
    dst.copy_from_slice(&conds[..n]);
    // SAFETY: FFI-boundary; pointer validity is the caller's contract per crate-level docs.
    unsafe { *out_count = n };
    ZeroDdsStatus::Ok as c_int
}

// suppress unused-import warning
#[allow(dead_code)]
fn _suppress(_: *mut ZeroDdsDataWriter) {}

#[cfg(test)]
#[allow(clippy::expect_used, clippy::unwrap_used, clippy::panic)]
mod tests {
    use super::*;

    #[test]
    fn guardcondition_lifecycle_and_trigger() {
        let g = zerodds_guardcondition_create();
        assert!(!g.is_null());
        // SAFETY: FFI-boundary; pointer validity is the caller's contract per crate-level docs.
        assert!(!unsafe { zerodds_condition_get_trigger_value(g as *const _) });
        // SAFETY: FFI-boundary; pointer validity is the caller's contract per crate-level docs.
        let _ = unsafe { zerodds_guardcondition_set_trigger_value(g, true) };
        // SAFETY: FFI-boundary; pointer validity is the caller's contract per crate-level docs.
        assert!(unsafe { zerodds_condition_get_trigger_value(g as *const _) });
        // SAFETY: FFI-boundary; pointer validity is the caller's contract per crate-level docs.
        unsafe { zerodds_guardcondition_destroy(g) };
    }

    #[test]
    fn statuscondition_lifecycle_and_mask() {
        // SAFETY: FFI-boundary; pointer validity is the caller's contract per crate-level docs.
        let sc = unsafe { zerodds_entity_get_statuscondition(ptr::null_mut()) };
        assert!(!sc.is_null());
        // SAFETY: FFI-boundary; pointer validity is the caller's contract per crate-level docs.
        let _ = unsafe { zerodds_statuscondition_set_enabled_statuses(sc, 0x1234) };
        assert_eq!(
            // SAFETY: FFI-boundary; pointer validity is the caller's contract per crate-level docs.
            unsafe { zerodds_statuscondition_get_enabled_statuses(sc) },
            0x1234
        );
        // SAFETY: FFI-boundary; pointer validity is the caller's contract per crate-level docs.
        unsafe { zerodds_statuscondition_destroy(sc) };
    }

    #[test]
    fn waitset_attach_detach() {
        let ws = zerodds_waitset_create();
        let g = zerodds_guardcondition_create();
        // SAFETY: FFI-boundary; pointer validity is the caller's contract per crate-level docs.
        let rc = unsafe { zerodds_waitset_attach_condition(ws, g as *mut core::ffi::c_void) };
        assert_eq!(rc, ZeroDdsStatus::Ok as c_int);
        let mut buf: [*mut core::ffi::c_void; 4] = [ptr::null_mut(); 4];
        let mut count: usize = 0;
        // SAFETY: FFI-boundary; pointer validity is the caller's contract per crate-level docs.
        let rc = unsafe { zerodds_waitset_get_conditions(ws, buf.as_mut_ptr(), 4, &mut count) };
        assert_eq!(rc, ZeroDdsStatus::Ok as c_int);
        assert_eq!(count, 1);
        // SAFETY: FFI-boundary; pointer validity is the caller's contract per crate-level docs.
        let rc = unsafe { zerodds_waitset_detach_condition(ws, g as *mut core::ffi::c_void) };
        assert_eq!(rc, ZeroDdsStatus::Ok as c_int);
        // SAFETY: FFI-boundary; pointer validity is the caller's contract per crate-level docs.
        unsafe { zerodds_waitset_destroy(ws) };
        // SAFETY: FFI-boundary; pointer validity is the caller's contract per crate-level docs.
        unsafe { zerodds_guardcondition_destroy(g) };
    }

    #[test]
    fn waitset_wait_returns_active_guard() {
        let ws = zerodds_waitset_create();
        let g = zerodds_guardcondition_create();
        // SAFETY: FFI-boundary; pointer validity is the caller's contract per crate-level docs.
        unsafe { zerodds_guardcondition_set_trigger_value(g, true) };
        // SAFETY: FFI-boundary; pointer validity is the caller's contract per crate-level docs.
        unsafe { zerodds_waitset_attach_condition(ws, g as *mut core::ffi::c_void) };
        let mut buf: [*mut core::ffi::c_void; 4] = [ptr::null_mut(); 4];
        let mut count: usize = 0;
        // SAFETY: FFI-boundary; pointer validity is the caller's contract per crate-level docs.
        let rc = unsafe { zerodds_waitset_wait(ws, buf.as_mut_ptr(), 4, &mut count, 1, 0) };
        assert_eq!(rc, ZeroDdsStatus::Ok as c_int);
        assert_eq!(count, 1);
        assert_eq!(buf[0], g as *mut core::ffi::c_void);
        // SAFETY: FFI-boundary; pointer validity is the caller's contract per crate-level docs.
        unsafe { zerodds_waitset_destroy(ws) };
        // SAFETY: FFI-boundary; pointer validity is the caller's contract per crate-level docs.
        unsafe { zerodds_guardcondition_destroy(g) };
    }

    #[test]
    fn waitset_wait_timeout_no_active() {
        let ws = zerodds_waitset_create();
        let g = zerodds_guardcondition_create();
        // SAFETY: FFI-boundary; pointer validity is the caller's contract per crate-level docs.
        unsafe { zerodds_waitset_attach_condition(ws, g as *mut core::ffi::c_void) };
        let mut buf: [*mut core::ffi::c_void; 4] = [ptr::null_mut(); 4];
        let mut count: usize = 0;
        let rc =
            // SAFETY: FFI-boundary; pointer validity is the caller's contract per crate-level docs.
            unsafe { zerodds_waitset_wait(ws, buf.as_mut_ptr(), 4, &mut count, 0, 50_000_000) };
        assert_eq!(rc, ZeroDdsStatus::Timeout as c_int);
        assert_eq!(count, 0);
        // SAFETY: FFI-boundary; pointer validity is the caller's contract per crate-level docs.
        unsafe { zerodds_waitset_destroy(ws) };
        // SAFETY: FFI-boundary; pointer validity is the caller's contract per crate-level docs.
        unsafe { zerodds_guardcondition_destroy(g) };
    }
}