signedby-sdk 0.1.0-beta.15

SIGNEDBYME SDK - Human-Controlled Identity for Autonomous Agents
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
// ffi.rs - OpenClaw Language Bindings (Phase 9A.7)
//
// Per Bible Section 9A.7 and line 638:
// "Rust core. OpenClaw bindings first (v1 priority)."
//
// C-compatible FFI bindings that enable maximum agent deployment flexibility
// across all platforms and programming languages.
//
// Error handling:
// - Return 0 for success, negative codes for errors
// - String functions return NULL on failure
//
// Memory safety:
// - All returned strings must be freed with agent_string_free()
// - Caller owns strings returned from FFI functions

use std::ffi::{CStr, CString};
use std::os::raw::{c_char, c_int};
use std::sync::Mutex;
use once_cell::sync::Lazy;
use serde_json;
use tokio::runtime::Runtime;

use crate::sdk::identity::{AgentIdentity, AgentIdentityState};
use crate::sdk::storage::EncryptedFileStorage;
use crate::sdk::nostr_client::NostrClient;
use crate::sdk::enrollment::EnrollmentBootstrap;

/// Global tokio runtime for async operations
static TOKIO_RUNTIME: Lazy<Runtime> = Lazy::new(|| {
    Runtime::new().expect("Failed to create tokio runtime")
});

// Error codes
pub const FFI_SUCCESS: c_int = 0;
pub const FFI_ERROR_NULL_POINTER: c_int = -1;
pub const FFI_ERROR_INVALID_UTF8: c_int = -2;
pub const FFI_ERROR_NOT_INITIALIZED: c_int = -3;
pub const FFI_ERROR_ALREADY_INITIALIZED: c_int = -4;
pub const FFI_ERROR_STORAGE_FAILED: c_int = -5;
pub const FFI_ERROR_ENROLLMENT_FAILED: c_int = -6;
pub const FFI_ERROR_AUTH_FAILED: c_int = -7;
pub const FFI_ERROR_DELEGATION_INVALID: c_int = -8;
pub const FFI_ERROR_WALLET_FAILED: c_int = -9;
pub const FFI_ERROR_INTERNAL: c_int = -100;

/// Global agent state (thread-safe singleton)
static AGENT_STATE: Lazy<Mutex<Option<AgentState>>> = Lazy::new(|| Mutex::new(None));

/// Internal agent state
struct AgentState {
    identity: AgentIdentityState,
    storage_path: String,
    nwc_uri: Option<String>,
    /// Email mapping: enterprise client_id → email address
    email_mapping: std::collections::HashMap<String, String>,
    /// Pending enrollment client_id (set when kind 28200 detected)
    pending_client_id: Option<String>,
    /// Pending enrollment email (set when kind 28200 detected)
    pending_email: Option<String>,
}

// ============================================================================
// Agent Lifecycle
// ============================================================================

/// Initialize the agent with default storage location
/// 
/// Returns: 0 on success, negative error code on failure
/// 
/// # Safety
/// This function is safe to call from C code.
#[no_mangle]
pub extern "C" fn agent_initialize() -> c_int {
    agent_initialize_with_path(std::ptr::null())
}

/// Initialize the agent with custom storage path
/// 
/// # Arguments
/// * `storage_path` - Path to storage directory (NULL for default ~/.signedby)
/// 
/// Returns: 0 on success, negative error code on failure
/// 
/// # Safety
/// This function is safe to call from C code. `storage_path` must be a valid
/// C string or NULL.
#[no_mangle]
pub extern "C" fn agent_initialize_with_path(storage_path: *const c_char) -> c_int {
    let mut state = match AGENT_STATE.lock() {
        Ok(s) => s,
        Err(_) => return FFI_ERROR_INTERNAL,
    };
    
    if state.is_some() {
        return FFI_ERROR_ALREADY_INITIALIZED;
    }
    
    // Determine storage path
    let path = if storage_path.is_null() {
        // Default: ~/.signedby
        match dirs::home_dir() {
            Some(home) => home.join(".signedby"),
            None => return FFI_ERROR_STORAGE_FAILED,
        }
    } else {
        let path_str = match unsafe { CStr::from_ptr(storage_path) }.to_str() {
            Ok(s) => s,
            Err(_) => return FFI_ERROR_INVALID_UTF8,
        };
        std::path::PathBuf::from(path_str)
    };
    
    // Create storage
    let storage = match EncryptedFileStorage::new(path.clone()) {
        Ok(s) => s,
        Err(_) => return FFI_ERROR_STORAGE_FAILED,
    };
    
    // Create or load identity
    let identity = AgentIdentity::new(storage);
    
    let identity_state = if identity.is_initialized() {
        match identity.load() {
            Ok(s) => s,
            Err(_) => return FFI_ERROR_STORAGE_FAILED,
        }
    } else {
        match identity.initialize() {
            Ok(s) => s,
            Err(_) => return FFI_ERROR_STORAGE_FAILED,
        }
    };
    
    *state = Some(AgentState {
        identity: identity_state,
        storage_path: path.to_string_lossy().to_string(),
        nwc_uri: None,
        email_mapping: std::collections::HashMap::new(),
        pending_client_id: None,
        pending_email: None,
    });
    
    FFI_SUCCESS
}

/// Get the agent's npub (NOSTR public key in bech32 format)
/// 
/// Returns: Newly allocated string on success, NULL on failure
/// Caller must free the returned string with agent_string_free()
/// 
/// # Safety
/// This function is safe to call from C code.
#[no_mangle]
pub extern "C" fn agent_get_npub() -> *mut c_char {
    let state = match AGENT_STATE.lock() {
        Ok(s) => s,
        Err(_) => return std::ptr::null_mut(),
    };
    
    let agent_state = match state.as_ref() {
        Some(s) => s,
        None => return std::ptr::null_mut(),
    };
    
    match CString::new(agent_state.identity.agent_npub.clone()) {
        Ok(s) => s.into_raw(),
        Err(_) => std::ptr::null_mut(),
    }
}

/// Get the agent's DID (Decentralized Identifier)
/// 
/// Returns: Newly allocated string on success, NULL on failure
/// Caller must free the returned string with agent_string_free()
/// 
/// # Safety
/// This function is safe to call from C code.
#[no_mangle]
pub extern "C" fn agent_get_did() -> *mut c_char {
    let state = match AGENT_STATE.lock() {
        Ok(s) => s,
        Err(_) => return std::ptr::null_mut(),
    };
    
    let agent_state = match state.as_ref() {
        Some(s) => s,
        None => return std::ptr::null_mut(),
    };
    
    match CString::new(agent_state.identity.did.clone()) {
        Ok(s) => s.into_raw(),
        Err(_) => std::ptr::null_mut(),
    }
}

/// Get the agent's leaf commitment (for enrollment verification)
/// 
/// Returns: Newly allocated hex string on success, NULL on failure
/// Caller must free the returned string with agent_string_free()
/// 
/// # Safety
/// This function is safe to call from C code.
#[no_mangle]
pub extern "C" fn agent_get_leaf_commitment() -> *mut c_char {
    let state = match AGENT_STATE.lock() {
        Ok(s) => s,
        Err(_) => return std::ptr::null_mut(),
    };
    
    let agent_state = match state.as_ref() {
        Some(s) => s,
        None => return std::ptr::null_mut(),
    };
    
    match CString::new(agent_state.identity.leaf_commitment.clone()) {
        Ok(s) => s.into_raw(),
        Err(_) => std::ptr::null_mut(),
    }
}

// ============================================================================
// Enterprise Integration
// ============================================================================

/// Enroll the agent with an enterprise
/// 
/// # Arguments
/// * `enterprise_domain` - Enterprise domain (e.g., "acme.com")
/// 
/// Returns: 0 on success, negative error code on failure
/// 
/// # Safety
/// This function is safe to call from C code. `enterprise_domain` must be
/// a valid C string.
#[no_mangle]
pub extern "C" fn agent_enroll(enterprise_domain: *const c_char) -> c_int {
    if enterprise_domain.is_null() {
        return FFI_ERROR_NULL_POINTER;
    }
    
    let _domain = match unsafe { CStr::from_ptr(enterprise_domain) }.to_str() {
        Ok(s) => s,
        Err(_) => return FFI_ERROR_INVALID_UTF8,
    };
    
    let state = match AGENT_STATE.lock() {
        Ok(s) => s,
        Err(_) => return FFI_ERROR_INTERNAL,
    };
    
    if state.is_none() {
        return FFI_ERROR_NOT_INITIALIZED;
    }
    
    // TODO: Implement enrollment via EnrollmentBootstrap
    // This requires async runtime, will be implemented in Phase 9A.8
    
    FFI_SUCCESS
}

/// Set email mapping for enterprises
/// 
/// Per Bible: "During SDK setup the human tells the agent their email address for each enterprise"
/// 
/// # Arguments
/// * `mappings_json` - JSON object: {"amazon": "me@gmail.com", "acme": "me@gmail.com"}
///                     Keys are client_id (not domain), values are email addresses
/// 
/// Returns: 0 on success, negative error code on failure
/// 
/// # Safety
/// This function is safe to call from C code. `mappings_json` must be a valid C string.
#[no_mangle]
pub extern "C" fn agent_set_email_mapping(mappings_json: *const c_char) -> c_int {
    if mappings_json.is_null() {
        return FFI_ERROR_NULL_POINTER;
    }
    
    let json_str = match unsafe { CStr::from_ptr(mappings_json) }.to_str() {
        Ok(s) => s,
        Err(_) => return FFI_ERROR_INVALID_UTF8,
    };
    
    // Parse JSON
    let mapping: std::collections::HashMap<String, String> = match serde_json::from_str(json_str) {
        Ok(m) => m,
        Err(_) => return FFI_ERROR_INTERNAL,
    };
    
    // Store in agent state
    let mut state = match AGENT_STATE.lock() {
        Ok(s) => s,
        Err(_) => return FFI_ERROR_INTERNAL,
    };
    
    let agent_state = match state.as_mut() {
        Some(s) => s,
        None => return FFI_ERROR_NOT_INITIALIZED,
    };
    
    agent_state.email_mapping = mapping;
    
    FFI_SUCCESS
}

/// Callback type for enrollment events
/// 
/// # Arguments
/// * `event_type` - 1=gate1_responding, 2=gate2_received, 3=enrollment_complete
/// * `event_json` - JSON payload with event details
pub type EnrollmentCallback = extern "C" fn(event_type: c_int, event_json: *const c_char);

/// Start the enrollment watcher (Option A: SDK handles everything)
/// 
/// Per Bible Gates 1-3:
/// - Subscribes to relay for kind 28200 events
/// - Auto-responds with kind 28202 when open session detected
/// - Waits for human to sign kind 28250
/// - Calls /v1/membership/enroll/commit automatically
/// 
/// # Arguments
/// * `callback` - Called at each gate completion with (event_type, event_json)
/// 
/// Returns: 0 on success (watcher started), negative error code on failure
/// 
/// # Safety
/// This function spawns a background task. The callback will be invoked
/// from a different thread. Ensure the callback is thread-safe.
#[no_mangle]
pub extern "C" fn agent_start_enrollment_watcher(callback: EnrollmentCallback) -> c_int {
    let state = match AGENT_STATE.lock() {
        Ok(s) => s,
        Err(_) => return FFI_ERROR_INTERNAL,
    };
    
    if state.is_none() {
        return FFI_ERROR_NOT_INITIALIZED;
    }
    
    let agent_state = state.as_ref().unwrap();
    
    if agent_state.email_mapping.is_empty() {
        // Must set email mapping first
        return FFI_ERROR_ENROLLMENT_FAILED;
    }
    
    // Callback will be invoked when:
    // - event_type=1: Gate 1 - publishing kind 28202 response
    // - event_type=2: Gate 2 - received authorization or delegation
    // - event_type=3: Enrollment complete (event_json contains result)
    
    let email_mapping = agent_state.email_mapping.clone();
    let storage_path = agent_state.storage_path.clone();
    drop(state); // Release lock before async work
    
    // Spawn enrollment watcher in background
    TOKIO_RUNTIME.spawn(async move {
        // Create storage
        let storage = match EncryptedFileStorage::new(std::path::PathBuf::from(&storage_path)) {
            Ok(s) => s,
            Err(e) => {
                eprintln!("[ffi] Failed to create storage: {}", e);
                return;
            }
        };
        
        // Create identity
        let identity = AgentIdentity::new(storage);
        
        // Create NostrClient
        let nostr_client = match NostrClient::new(&identity).await {
            Ok(c) => c,
            Err(e) => {
                eprintln!("[ffi] Failed to create NostrClient: {}", e);
                return;
            }
        };
        
        // Create EnrollmentBootstrap
        let mut enrollment = EnrollmentBootstrap::new(
            nostr_client,
            "https://api.signedbyme.com".to_string(),
            email_mapping,
        );
        
        // Start watcher with callbacks
        let callback_gate = callback;
        let callback_complete = callback;
        
        let _ = enrollment.start_enrollment_watcher(
            &identity,
            move |gate, msg| {
                if let Ok(msg_cstr) = CString::new(msg) {
                    callback_gate(gate as c_int, msg_cstr.as_ptr());
                }
            },
            move |result| {
                if let Ok(json) = serde_json::to_string(&result) {
                    if let Ok(json_cstr) = CString::new(json) {
                        callback_complete(3, json_cstr.as_ptr());
                    }
                }
            },
        ).await;
    });
    
    FFI_SUCCESS
}

/// Submit the challenge code entered by the human (Gate 1 completion)
/// 
/// Per Bible: "The human manually enters the challenge code into the agent"
/// Call this after receiving the gate=1 callback with the challenge code
/// displayed on the enterprise screen.
/// 
/// # Arguments
/// * `client_id` - Enterprise client ID from the gate 1 callback
/// * `email` - Email address for this enterprise
/// * `challenge` - Challenge code entered by the human
/// 
/// Returns: 0 on success, negative error code on failure
/// 
/// # Safety
/// This function is safe to call from C code.
#[no_mangle]
pub extern "C" fn agent_submit_challenge_code(
    client_id: *const c_char,
    email: *const c_char,
    challenge: *const c_char,
) -> c_int {
    if client_id.is_null() || email.is_null() || challenge.is_null() {
        return FFI_ERROR_NULL_POINTER;
    }
    
    let client_id_str = match unsafe { CStr::from_ptr(client_id) }.to_str() {
        Ok(s) => s,
        Err(_) => return FFI_ERROR_INVALID_UTF8,
    };
    
    let email_str = match unsafe { CStr::from_ptr(email) }.to_str() {
        Ok(s) => s,
        Err(_) => return FFI_ERROR_INVALID_UTF8,
    };
    
    let challenge_str = match unsafe { CStr::from_ptr(challenge) }.to_str() {
        Ok(s) => s,
        Err(_) => return FFI_ERROR_INVALID_UTF8,
    };
    
    let state = match AGENT_STATE.lock() {
        Ok(s) => s,
        Err(_) => return FFI_ERROR_INTERNAL,
    };
    
    if state.is_none() {
        return FFI_ERROR_NOT_INITIALIZED;
    }
    
    let agent_state = state.as_ref().unwrap();
    let storage_path = agent_state.storage_path.clone();
    let email_mapping = agent_state.email_mapping.clone();
    drop(state);
    
    // Run async publishing in the tokio runtime
    let result = TOKIO_RUNTIME.block_on(async {
        // Create storage
        let storage = match EncryptedFileStorage::new(std::path::PathBuf::from(&storage_path)) {
            Ok(s) => s,
            Err(e) => {
                eprintln!("[ffi] Failed to create storage: {}", e);
                return Err(());
            }
        };
        
        // Create identity
        let identity = AgentIdentity::new(storage);
        
        // Create NostrClient
        let nostr_client = match NostrClient::new(&identity).await {
            Ok(c) => c,
            Err(e) => {
                eprintln!("[ffi] Failed to create NostrClient: {}", e);
                return Err(());
            }
        };
        
        // Create EnrollmentBootstrap
        let enrollment = EnrollmentBootstrap::new(
            nostr_client,
            "https://api.signedbyme.com".to_string(),
            email_mapping,
        );
        
        // Submit the challenge code
        match enrollment.submit_challenge_code(client_id_str, email_str, challenge_str).await {
            Ok(event_id) => {
                eprintln!("[ffi] Gate 1 complete: Published kind 28202: {}", event_id);
                Ok(())
            }
            Err(e) => {
                eprintln!("[ffi] Failed to submit challenge: {}", e);
                Err(())
            }
        }
    });
    
    match result {
        Ok(()) => FFI_SUCCESS,
        Err(()) => FFI_ERROR_ENROLLMENT_FAILED,
    }
}

/// Authenticate with an enterprise (generate and submit proof)
/// 
/// # Arguments
/// * `enterprise_domain` - Enterprise domain (e.g., "acme.com")
/// 
/// Returns: OIDC id_token on success, NULL on failure
/// Caller must free the returned string with agent_string_free()
/// 
/// # Safety
/// This function is safe to call from C code. `enterprise_domain` must be
/// a valid C string.
#[no_mangle]
pub extern "C" fn agent_authenticate(enterprise_domain: *const c_char) -> *mut c_char {
    if enterprise_domain.is_null() {
        return std::ptr::null_mut();
    }
    
    let _domain = match unsafe { CStr::from_ptr(enterprise_domain) }.to_str() {
        Ok(s) => s,
        Err(_) => return std::ptr::null_mut(),
    };
    
    let state = match AGENT_STATE.lock() {
        Ok(s) => s,
        Err(_) => return std::ptr::null_mut(),
    };
    
    if state.is_none() {
        return std::ptr::null_mut();
    }
    
    // TODO: Implement authentication via MembershipProver
    // This requires async runtime and proof generation, will be implemented in Phase 9A.8
    
    std::ptr::null_mut()
}

// ============================================================================
// Delegation Management
// ============================================================================

/// Check if delegation from human owner is valid
/// 
/// # Arguments
/// * `enterprise_domain` - Enterprise domain (e.g., "acme.com")
/// 
/// Returns: 1 if valid, 0 if invalid/expired/revoked, negative on error
/// 
/// # Safety
/// This function is safe to call from C code. `enterprise_domain` must be
/// a valid C string.
#[no_mangle]
pub extern "C" fn agent_check_delegation(enterprise_domain: *const c_char) -> c_int {
    if enterprise_domain.is_null() {
        return FFI_ERROR_NULL_POINTER;
    }
    
    let _domain = match unsafe { CStr::from_ptr(enterprise_domain) }.to_str() {
        Ok(s) => s,
        Err(_) => return FFI_ERROR_INVALID_UTF8,
    };
    
    let state = match AGENT_STATE.lock() {
        Ok(s) => s,
        Err(_) => return FFI_ERROR_INTERNAL,
    };
    
    if state.is_none() {
        return FFI_ERROR_NOT_INITIALIZED;
    }
    
    // TODO: Implement delegation check via DelegationValidator
    // This requires async runtime, will be implemented in Phase 9A.8
    
    1 // Assume valid for now
}

// ============================================================================
// Wallet Operations
// ============================================================================

/// Setup NWC wallet connection
/// 
/// # Arguments
/// * `nwc_uri` - NWC connection URI (nostr+walletconnect://...)
/// 
/// Returns: 0 on success, negative error code on failure
/// 
/// # Safety
/// This function is safe to call from C code. `nwc_uri` must be a valid C string.
#[no_mangle]
pub extern "C" fn agent_setup_wallet(nwc_uri: *const c_char) -> c_int {
    if nwc_uri.is_null() {
        return FFI_ERROR_NULL_POINTER;
    }
    
    let uri = match unsafe { CStr::from_ptr(nwc_uri) }.to_str() {
        Ok(s) => s,
        Err(_) => return FFI_ERROR_INVALID_UTF8,
    };
    
    // Validate URI format
    if !uri.starts_with("nostr+walletconnect://") {
        return FFI_ERROR_WALLET_FAILED;
    }
    
    let mut state = match AGENT_STATE.lock() {
        Ok(s) => s,
        Err(_) => return FFI_ERROR_INTERNAL,
    };
    
    let agent_state = match state.as_mut() {
        Some(s) => s,
        None => return FFI_ERROR_NOT_INITIALIZED,
    };
    
    agent_state.nwc_uri = Some(uri.to_string());
    
    FFI_SUCCESS
}

/// Get the agent's Lightning address (if published)
/// 
/// Returns: Lightning address string on success, NULL if not set
/// Caller must free the returned string with agent_string_free()
/// 
/// # Safety
/// This function is safe to call from C code.
#[no_mangle]
pub extern "C" fn agent_get_lightning_address() -> *mut c_char {
    // TODO: Implement - retrieve from NOSTR kind 0 profile
    std::ptr::null_mut()
}

/// Create an invoice for receiving payment
/// 
/// # Arguments
/// * `amount_sats` - Amount in satoshis
/// * `description` - Invoice description
/// 
/// Returns: BOLT11 invoice string on success, NULL on failure
/// Caller must free the returned string with agent_string_free()
/// 
/// # Safety
/// This function is safe to call from C code. `description` must be a valid C string.
#[no_mangle]
pub extern "C" fn agent_create_invoice(
    amount_sats: u64,
    description: *const c_char,
) -> *mut c_char {
    if description.is_null() {
        return std::ptr::null_mut();
    }
    
    let _desc = match unsafe { CStr::from_ptr(description) }.to_str() {
        Ok(s) => s,
        Err(_) => return std::ptr::null_mut(),
    };
    
    let state = match AGENT_STATE.lock() {
        Ok(s) => s,
        Err(_) => return std::ptr::null_mut(),
    };
    
    let agent_state = match state.as_ref() {
        Some(s) => s,
        None => return std::ptr::null_mut(),
    };
    
    if agent_state.nwc_uri.is_none() {
        return std::ptr::null_mut();
    }
    
    // TODO: Implement via NwcWallet.create_receive_invoice()
    // This requires async runtime, will be implemented in Phase 9A.8
    let _ = amount_sats;
    
    std::ptr::null_mut()
}

/// Pay a BOLT11 invoice
/// 
/// # Arguments
/// * `bolt11` - BOLT11 invoice string
/// 
/// Returns: Payment preimage hex on success, NULL on failure
/// Caller must free the returned string with agent_string_free()
/// 
/// # Safety
/// This function is safe to call from C code. `bolt11` must be a valid C string.
#[no_mangle]
pub extern "C" fn agent_pay_invoice(bolt11: *const c_char) -> *mut c_char {
    if bolt11.is_null() {
        return std::ptr::null_mut();
    }
    
    let _invoice = match unsafe { CStr::from_ptr(bolt11) }.to_str() {
        Ok(s) => s,
        Err(_) => return std::ptr::null_mut(),
    };
    
    let state = match AGENT_STATE.lock() {
        Ok(s) => s,
        Err(_) => return std::ptr::null_mut(),
    };
    
    let agent_state = match state.as_ref() {
        Some(s) => s,
        None => return std::ptr::null_mut(),
    };
    
    if agent_state.nwc_uri.is_none() {
        return std::ptr::null_mut();
    }
    
    // TODO: Implement via NwcWallet.pay_invoice()
    // This requires async runtime, will be implemented in Phase 9A.8
    
    std::ptr::null_mut()
}

/// Get wallet balance in satoshis
/// 
/// Returns: Balance in sats on success, -1 on failure
/// 
/// # Safety
/// This function is safe to call from C code.
#[no_mangle]
pub extern "C" fn agent_get_balance() -> i64 {
    let state = match AGENT_STATE.lock() {
        Ok(s) => s,
        Err(_) => return -1,
    };
    
    let agent_state = match state.as_ref() {
        Some(s) => s,
        None => return -1,
    };
    
    if agent_state.nwc_uri.is_none() {
        return -1;
    }
    
    // TODO: Implement via NwcWallet.get_balance()
    // This requires async runtime, will be implemented in Phase 9A.8
    
    -1
}

// ============================================================================
// Memory Management
// ============================================================================

/// Free a string allocated by the FFI layer
/// 
/// # Arguments
/// * `ptr` - Pointer to string previously returned by an agent_* function
/// 
/// # Safety
/// This function must only be called with pointers returned by agent_* functions.
/// Calling with any other pointer is undefined behavior.
#[no_mangle]
pub extern "C" fn agent_string_free(ptr: *mut c_char) {
    if !ptr.is_null() {
        unsafe {
            let _ = CString::from_raw(ptr);
        }
    }
}

// ============================================================================
// Utility Functions
// ============================================================================

/// Get the SDK version string
/// 
/// Returns: Version string (e.g., "0.3.0")
/// Caller must free the returned string with agent_string_free()
/// 
/// # Safety
/// This function is safe to call from C code.
#[no_mangle]
pub extern "C" fn agent_sdk_version() -> *mut c_char {
    match CString::new(env!("CARGO_PKG_VERSION")) {
        Ok(s) => s.into_raw(),
        Err(_) => std::ptr::null_mut(),
    }
}

/// Check if the agent is initialized
/// 
/// Returns: 1 if initialized, 0 if not
/// 
/// # Safety
/// This function is safe to call from C code.
#[no_mangle]
pub extern "C" fn agent_is_initialized() -> c_int {
    let state = match AGENT_STATE.lock() {
        Ok(s) => s,
        Err(_) => return 0,
    };
    
    if state.is_some() { 1 } else { 0 }
}

/// Shutdown the agent and release resources
/// 
/// Returns: 0 on success
/// 
/// # Safety
/// This function is safe to call from C code.
#[no_mangle]
pub extern "C" fn agent_shutdown() -> c_int {
    let mut state = match AGENT_STATE.lock() {
        Ok(s) => s,
        Err(_) => return FFI_ERROR_INTERNAL,
    };
    
    *state = None;
    FFI_SUCCESS
}

#[cfg(test)]
mod tests {
    use super::*;
    
    #[test]
    fn test_sdk_version() {
        let version = agent_sdk_version();
        assert!(!version.is_null());
        unsafe {
            let _ = CString::from_raw(version);
        }
    }
    
    #[test]
    fn test_not_initialized() {
        // Reset state for test
        {
            let mut state = AGENT_STATE.lock().unwrap();
            *state = None;
        }
        
        assert_eq!(agent_is_initialized(), 0);
        assert!(agent_get_npub().is_null());
    }
}