reinhardt-apps 0.1.2

Application registry and management for Reinhardt framework
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
//! # Application Registry
//!
//! Django-inspired application configuration and registry system.
//! This module provides the infrastructure for managing Django-style apps
//! in a Reinhardt project.
//!
//! This module provides both string-based (runtime) and type-safe (compile-time)
//! application registry mechanisms.

use crate::signals;
use std::collections::HashMap;
use std::error::Error;
use std::sync::{Arc, Mutex, PoisonError};
use thiserror::Error as ThisError;

/// Errors that can occur when working with the application registry
#[derive(Debug, ThisError)]
pub enum AppError {
	/// The requested application was not found in the registry.
	#[error("Application not found: {0}")]
	NotFound(String),

	/// An application with the same label is already registered.
	#[error("Application already registered: {0}")]
	AlreadyRegistered(String),

	/// The provided application label is invalid.
	#[error("Invalid application label: {0}")]
	InvalidLabel(String),

	/// Two applications share the same label.
	#[error("Duplicate application label: {0}")]
	DuplicateLabel(String),

	/// Two applications share the same name.
	#[error("Duplicate application name: {0}")]
	DuplicateName(String),

	/// The application registry has not been initialized yet.
	#[error("Application registry not ready")]
	NotReady,

	/// A configuration error occurred during application setup.
	#[error("Application configuration error: {0}")]
	ConfigError(String),

	/// An error related to the internal state of the registry.
	#[error("Registry state error: {0}")]
	RegistryState(String),
}

/// A specialized `Result` type for application operations.
pub type AppResult<T> = Result<T, AppError>;

/// Configuration for a single application
#[derive(Clone, Debug)]
pub struct AppConfig {
	/// The full Python-style name of the application (e.g., "myapp" or "myproject.apps.MyAppConfig")
	pub name: String,

	/// The short label for the application (e.g., "myapp")
	pub label: String,

	/// Human-readable name for the application
	pub verbose_name: Option<String>,

	/// Filesystem path to the application
	pub path: Option<String>,

	/// Default auto field type for models in this app
	pub default_auto_field: Option<String>,

	/// Whether the app has been populated with models
	pub models_ready: bool,
}

/// Re-export of the vendor asset descriptor from `reinhardt-utils` so that the
/// `#[app_config]` attribute macro can refer to it via
/// `reinhardt_apps::AppVendorAsset` without forcing user crates to depend on
/// `reinhardt-utils` directly.
///
/// Native-only: `reinhardt-utils` currently pulls in tokio's `net` feature
/// (mio) and does not compile on `wasm32-unknown-unknown`.
#[cfg(native)]
pub use reinhardt_utils::staticfiles::vendor::AppVendorAsset;

impl AppConfig {
	/// Create a new AppConfig with required fields
	pub fn new(name: impl Into<String>, label: impl Into<String>) -> Self {
		Self {
			name: name.into(),
			label: label.into(),
			verbose_name: None,
			path: None,
			default_auto_field: None,
			models_ready: false,
		}
	}

	/// Set the verbose name for the application
	pub fn with_verbose_name(mut self, verbose_name: impl Into<String>) -> Self {
		self.verbose_name = Some(verbose_name.into());
		self
	}

	/// Set the path for the application.
	///
	/// The path is validated to reject path traversal sequences (`..`),
	/// absolute paths (starting with `/` or a Windows drive letter), and
	/// null bytes. These restrictions prevent path traversal attacks when
	/// the path is later used to locate application resources on disk.
	///
	/// # Errors
	///
	/// Returns [`AppError::ConfigError`] if the path contains disallowed
	/// sequences.
	pub fn with_path(mut self, path: impl Into<String>) -> AppResult<Self> {
		let path = path.into();
		Self::validate_path(&path)?;
		self.path = Some(path);
		Ok(self)
	}

	/// Validates an application path to prevent path traversal and injection.
	///
	/// Rejects paths that contain:
	/// - Path traversal sequences (`..`)
	/// - Absolute paths (starting with `/` or a Windows drive letter like `C:\`)
	/// - Null bytes (`\0`)
	/// - Control characters
	fn validate_path(path: &str) -> AppResult<()> {
		if path.is_empty() {
			return Err(AppError::ConfigError(
				"application path cannot be empty".to_string(),
			));
		}

		// Reject null bytes
		if path.contains('\0') {
			return Err(AppError::ConfigError(
				"application path must not contain null bytes".to_string(),
			));
		}

		// Reject control characters (prevents log injection)
		if path.chars().any(|c| c.is_control()) {
			return Err(AppError::ConfigError(
				"application path must not contain control characters".to_string(),
			));
		}

		// Reject absolute paths (Unix-style or Windows-style)
		if path.starts_with('/') || path.starts_with('\\') {
			return Err(AppError::ConfigError(
				"application path must be relative, not absolute".to_string(),
			));
		}

		// Reject Windows drive letter paths (e.g., C:\, D:/)
		if path.len() >= 2 && path.as_bytes()[0].is_ascii_alphabetic() && path.as_bytes()[1] == b':'
		{
			return Err(AppError::ConfigError(
				"application path must be relative, not absolute".to_string(),
			));
		}

		// Reject path traversal sequences
		for component in path.split(['/', '\\']) {
			if component == ".." {
				return Err(AppError::ConfigError(
					"application path must not contain path traversal sequences".to_string(),
				));
			}
		}

		Ok(())
	}

	/// Set the default auto field for the application
	pub fn with_default_auto_field(mut self, field: impl Into<String>) -> Self {
		self.default_auto_field = Some(field.into());
		self
	}

	/// Validate the application label
	pub fn validate_label(&self) -> AppResult<()> {
		if self.label.is_empty() {
			return Err(AppError::InvalidLabel("Label cannot be empty".to_string()));
		}

		// Check if label is a valid Rust identifier
		if !self
			.label
			.chars()
			.next()
			.map(|c| c.is_alphabetic() || c == '_')
			.unwrap_or(false)
		{
			return Err(AppError::InvalidLabel(format!(
				"Label '{}' must start with a letter or underscore",
				self.label
			)));
		}

		if !self.label.chars().all(|c| c.is_alphanumeric() || c == '_') {
			return Err(AppError::InvalidLabel(format!(
				"Label '{}' must contain only alphanumeric characters and underscores",
				self.label
			)));
		}

		Ok(())
	}

	/// Ready hook for the application
	///
	/// This method is called when the application is ready, after all configurations
	/// have been loaded and models have been registered. Override this method in
	/// custom application configurations to perform initialization tasks.
	///
	/// # Examples
	///
	/// ```rust
	/// use reinhardt_apps::AppConfig;
	///
	/// let config = AppConfig::new("myapp", "myapp");
	/// config.ready().expect("Ready hook should succeed");
	/// ```
	pub fn ready(&self) -> Result<(), Box<dyn Error>> {
		// Default implementation does nothing
		// Applications can override this by implementing custom AppConfig structs
		Ok(())
	}
}

// ============================================================================
// Resource Provider Traits
// ============================================================================

/// Trait for providing static file directories
///
/// Applications can implement this trait to provide static files
/// that will be automatically discovered by collectstatic.
pub trait StaticFilesProvider {
	/// Get the static files directory for this app
	///
	/// Returns None if the app does not provide static files
	fn static_dir(&self) -> Option<std::path::PathBuf> {
		None
	}

	/// Get the static URL prefix for this app
	///
	/// Default: "/static/{app_label}/"
	fn static_url_prefix(&self) -> Option<String> {
		None
	}
}

/// Trait for providing locale directories
///
/// Applications can implement this trait to provide translation files
/// that will be automatically discovered by makemessages.
pub trait LocaleProvider {
	/// Get the locale directory for this app
	///
	/// Returns None if the app does not provide translations
	fn locale_dir(&self) -> Option<std::path::PathBuf> {
		None
	}
}

/// Trait for providing media directories
///
/// Applications can implement this trait to provide initial media files
/// that will be automatically discovered by collectmedia.
pub trait MediaProvider {
	/// Get the media directory for this app
	///
	/// Returns None if the app does not provide media files
	fn media_dir(&self) -> Option<std::path::PathBuf> {
		None
	}

	/// Get the media URL prefix for this app
	///
	/// Default: "/media/{app_label}/"
	fn media_url_prefix(&self) -> Option<String> {
		None
	}
}

/// Default implementations for AppConfig
impl StaticFilesProvider for AppConfig {
	fn static_dir(&self) -> Option<std::path::PathBuf> {
		// Default: {app_path}/static/
		if let Some(path) = &self.path {
			let static_path = std::path::PathBuf::from(path).join("static");
			if static_path.exists() && static_path.is_dir() {
				return Some(static_path);
			}
		}
		None
	}

	fn static_url_prefix(&self) -> Option<String> {
		Some(format!("/static/{}/", self.label))
	}
}

impl LocaleProvider for AppConfig {
	fn locale_dir(&self) -> Option<std::path::PathBuf> {
		// Default: {app_path}/locale/
		if let Some(path) = &self.path {
			let locale_path = std::path::PathBuf::from(path).join("locale");
			if locale_path.exists() && locale_path.is_dir() {
				return Some(locale_path);
			}
		}
		None
	}
}

impl MediaProvider for AppConfig {
	fn media_dir(&self) -> Option<std::path::PathBuf> {
		// Default: {app_path}/media/
		if let Some(path) = &self.path {
			let media_path = std::path::PathBuf::from(path).join("media");
			if media_path.exists() && media_path.is_dir() {
				return Some(media_path);
			}
		}
		None
	}

	fn media_url_prefix(&self) -> Option<String> {
		Some(format!("/media/{}/", self.label))
	}
}

/// Main application registry
///
/// This is the central registry for all installed applications in a Reinhardt project.
/// It manages application configuration, initialization order, and provides
/// methods to query installed applications.
#[derive(Clone)]
pub struct Apps {
	/// List of installed application identifiers
	installed_apps: Vec<String>,

	/// Map of application labels to their configurations
	app_configs: Arc<Mutex<HashMap<String, AppConfig>>>,

	/// Map of application names to their labels
	app_names: Arc<Mutex<HashMap<String, String>>>,

	/// Whether the registry has been populated
	ready: Arc<Mutex<bool>>,

	/// Whether app configs have been populated
	apps_ready: Arc<Mutex<bool>>,

	/// Whether models have been populated
	models_ready: Arc<Mutex<bool>>,
}

impl Apps {
	/// Create a new application registry
	pub fn new(installed_apps: Vec<String>) -> Self {
		Self {
			installed_apps,
			app_configs: Arc::new(Mutex::new(HashMap::new())),
			app_names: Arc::new(Mutex::new(HashMap::new())),
			ready: Arc::new(Mutex::new(false)),
			apps_ready: Arc::new(Mutex::new(false)),
			models_ready: Arc::new(Mutex::new(false)),
		}
	}

	/// Check if the registry is fully ready
	pub fn is_ready(&self) -> bool {
		*self.ready.lock().unwrap_or_else(PoisonError::into_inner)
	}

	/// Check if app configurations are ready
	pub fn is_apps_ready(&self) -> bool {
		*self
			.apps_ready
			.lock()
			.unwrap_or_else(PoisonError::into_inner)
	}

	/// Check if models are ready
	pub fn is_models_ready(&self) -> bool {
		*self
			.models_ready
			.lock()
			.unwrap_or_else(PoisonError::into_inner)
	}

	/// Register an application configuration
	pub fn register(&self, config: AppConfig) -> AppResult<()> {
		// Validate the configuration
		config.validate_label()?;

		let mut configs = self
			.app_configs
			.lock()
			.unwrap_or_else(PoisonError::into_inner);
		let mut names = self
			.app_names
			.lock()
			.unwrap_or_else(PoisonError::into_inner);

		// Check for duplicate label
		if configs.contains_key(&config.label) {
			return Err(AppError::DuplicateLabel(config.label.clone()));
		}

		// Check for duplicate name
		if names.contains_key(&config.name) {
			return Err(AppError::DuplicateName(config.name.clone()));
		}

		// Store the configuration
		names.insert(config.name.clone(), config.label.clone());
		configs.insert(config.label.clone(), config);

		Ok(())
	}

	/// Get an application configuration by label
	pub fn get_app_config(&self, label: &str) -> AppResult<AppConfig> {
		self.app_configs
			.lock()
			.unwrap_or_else(PoisonError::into_inner)
			.get(label)
			.cloned()
			.ok_or_else(|| AppError::NotFound(label.to_string()))
	}

	/// Get all registered application configurations
	pub fn get_app_configs(&self) -> Vec<AppConfig> {
		self.app_configs
			.lock()
			.unwrap_or_else(PoisonError::into_inner)
			.values()
			.cloned()
			.collect()
	}

	/// Check if an application is installed
	///
	/// Acquires locks on both `app_names` and `app_configs` before checking,
	/// ensuring a consistent snapshot and avoiding TOCTOU race conditions
	/// where state could change between individual lock acquisitions.
	pub fn is_installed(&self, name: &str) -> bool {
		if self.installed_apps.contains(&name.to_string()) {
			return true;
		}

		// Hold both locks simultaneously for a consistent snapshot
		let names = self
			.app_names
			.lock()
			.unwrap_or_else(PoisonError::into_inner);
		let configs = self
			.app_configs
			.lock()
			.unwrap_or_else(PoisonError::into_inner);

		names.contains_key(name) || configs.contains_key(name)
	}

	/// Populate the registry with application configurations
	///
	/// This method initializes all registered applications by:
	/// 1. Creating AppConfig instances for each installed app
	/// 2. Calling the ready() method on each AppConfig
	/// 3. Loading model definitions from the global registry
	/// 4. Building reverse relations between models
	///
	/// # Examples
	///
	/// ```rust
	/// use reinhardt_apps::Apps;
	///
	/// let apps = Apps::new(vec!["myapp".to_string()]);
	/// apps.populate().expect("Failed to populate apps");
	/// ```
	pub fn populate(&self) -> AppResult<()> {
		// Mark as apps_ready
		*self
			.apps_ready
			.lock()
			.unwrap_or_else(PoisonError::into_inner) = true;

		// 1. Import and instantiate AppConfig for each installed app
		// Detect duplicate entries in the installed_apps list itself
		{
			let mut seen = std::collections::HashSet::new();
			for app_name in &self.installed_apps {
				if !seen.insert(app_name) {
					return Err(AppError::DuplicateLabel(app_name.clone()));
				}
			}
		}

		for app_name in &self.installed_apps {
			let app_config = AppConfig::new(app_name.clone(), app_name.clone());

			// Skip apps already registered via register() to avoid overwriting
			let mut configs = self
				.app_configs
				.lock()
				.unwrap_or_else(PoisonError::into_inner);
			if configs.contains_key(&app_config.label) {
				continue;
			}
			configs.insert(app_config.label.clone(), app_config.clone());
			drop(configs);

			self.app_names
				.lock()
				.unwrap_or_else(PoisonError::into_inner)
				.insert(app_name.clone(), app_config.label.clone());
		}

		// 2. Call ready() method on each AppConfig and send signals
		let configs = self
			.app_configs
			.lock()
			.unwrap_or_else(PoisonError::into_inner);
		for app_config in configs.values() {
			// Call the ready hook
			app_config.ready().map_err(|e| {
				AppError::ConfigError(format!(
					"Ready hook failed for app '{}': {}",
					app_config.label, e
				))
			})?;

			// Send the app_ready signal
			signals::app_ready().send(app_config);
		}
		drop(configs); // Release lock early

		// 3. Load model definitions from global ModelRegistry
		// The models are already registered via #[derive(Model)] macro
		// which automatically registers them at construction time

		// 4. Build reverse relations between models.
		//    The discovery + registry layers depend on `linkme` distributed
		//    slices and on server-only crates, so this step only runs on
		//    native targets. On `wasm32-unknown-unknown`, model registration
		//    is a no-op (the client never owns the model graph).
		#[cfg(native)]
		if !*self
			.models_ready
			.lock()
			.unwrap_or_else(PoisonError::into_inner)
		{
			crate::discovery::build_reverse_relations()?;
			// Finalize reverse relations to make them immutable
			crate::registry::finalize_reverse_relations();
		}

		// Mark as models_ready
		*self
			.models_ready
			.lock()
			.unwrap_or_else(PoisonError::into_inner) = true;
		*self.ready.lock().unwrap_or_else(PoisonError::into_inner) = true;

		Ok(())
	}

	/// Clear all cached data (for testing)
	pub fn clear_cache(&self) {
		self.app_configs
			.lock()
			.unwrap_or_else(PoisonError::into_inner)
			.clear();
		self.app_names
			.lock()
			.unwrap_or_else(PoisonError::into_inner)
			.clear();
		*self.ready.lock().unwrap_or_else(PoisonError::into_inner) = false;
		*self
			.apps_ready
			.lock()
			.unwrap_or_else(PoisonError::into_inner) = false;
		*self
			.models_ready
			.lock()
			.unwrap_or_else(PoisonError::into_inner) = false;
	}
}

// DI integration (feature-gated)
#[cfg(feature = "di")]
mod di_integration {
	use super::*;
	use reinhardt_di::{DiError, DiResult, Injectable, InjectionContext};

	#[async_trait::async_trait]
	impl Injectable for Apps {
		async fn inject(ctx: &InjectionContext) -> DiResult<Self> {
			// Get from singleton scope
			if let Some(apps) = ctx.get_singleton::<Apps>() {
				return Ok((*apps).clone());
			}

			Err(DiError::NotFound(std::any::type_name::<Apps>().to_string()))
		}
	}
}

#[cfg(test)]
mod tests {
	use super::*;
	use rstest::rstest;
	use serial_test::serial;

	#[rstest]
	fn test_app_config_creation() {
		// Arrange & Act
		let config = AppConfig::new("myapp", "myapp")
			.with_verbose_name("My Application")
			.with_default_auto_field("BigAutoField");

		// Assert
		assert_eq!(config.name, "myapp");
		assert_eq!(config.label, "myapp");
		assert_eq!(config.verbose_name, Some("My Application".to_string()));
		assert_eq!(config.default_auto_field, Some("BigAutoField".to_string()));
	}

	#[rstest]
	fn test_app_config_validation() {
		// Arrange
		let valid = AppConfig::new("myapp", "myapp");
		let invalid = AppConfig::new("myapp", "my-app");
		let empty = AppConfig::new("myapp", "");

		// Act & Assert
		assert!(valid.validate_label().is_ok());
		assert!(invalid.validate_label().is_err());
		assert!(empty.validate_label().is_err());
	}

	#[rstest]
	fn test_apps_registry() {
		// Arrange
		let apps = Apps::new(vec!["myapp".to_string(), "anotherapp".to_string()]);

		// Act & Assert
		assert!(apps.is_installed("myapp"));
		assert!(apps.is_installed("anotherapp"));
		assert!(!apps.is_installed("notinstalled"));
	}

	#[rstest]
	fn test_register_app() {
		// Arrange
		let apps = Apps::new(vec![]);
		let config = AppConfig::new("myapp", "myapp");

		// Act & Assert
		assert!(apps.register(config).is_ok());
		assert!(apps.get_app_config("myapp").is_ok());
	}

	#[rstest]
	fn test_duplicate_registration() {
		// Arrange
		let apps = Apps::new(vec![]);
		let config1 = AppConfig::new("myapp", "myapp");
		let config2 = AppConfig::new("myapp", "myapp");
		apps.register(config1).unwrap();

		// Act
		let result = apps.register(config2);

		// Assert
		assert!(result.is_err());
	}

	#[rstest]
	fn test_get_app_configs() {
		// Arrange
		let apps = Apps::new(vec![]);
		apps.register(AppConfig::new("app1", "app1")).unwrap();
		apps.register(AppConfig::new("app2", "app2")).unwrap();

		// Act
		let configs = apps.get_app_configs();

		// Assert
		assert_eq!(configs.len(), 2);
	}

	#[rstest]
	#[serial(apps_registry)]
	fn test_populate() {
		// Arrange - Reset global state before test
		crate::registry::reset_global_registry();

		// Arrange
		let apps = Apps::new(vec![]);
		assert!(!apps.is_ready());

		// Act
		apps.populate().unwrap();

		// Assert
		assert!(apps.is_ready());
		assert!(apps.is_apps_ready());
		assert!(apps.is_models_ready());
	}

	#[rstest]
	#[serial(apps_registry)]
	fn test_populate_with_installed_apps() {
		// Arrange - Reset global state before test
		crate::registry::reset_global_registry();

		// Arrange
		let apps = Apps::new(vec!["myapp".to_string(), "anotherapp".to_string()]);
		assert!(!apps.is_ready());

		// Act
		let result = apps.populate();

		// Assert
		assert!(result.is_ok());
		assert!(apps.is_ready());
		assert!(apps.is_apps_ready());
		assert!(apps.is_models_ready());
		assert!(apps.get_app_config("myapp").is_ok());
		assert!(apps.get_app_config("anotherapp").is_ok());
		let myapp_config = apps.get_app_config("myapp").unwrap();
		assert_eq!(myapp_config.label, "myapp");
	}

	// ==========================================================================
	// Path Validation Tests
	// ==========================================================================

	#[rstest]
	#[case("apps/myapp")]
	#[case("myapp")]
	#[case("src/apps/myapp")]
	#[case("my_app")]
	#[case("my-app")]
	fn test_with_path_accepts_valid_relative_paths(#[case] path: &str) {
		// Act
		let result = AppConfig::new("myapp", "myapp").with_path(path);

		// Assert
		assert!(result.is_ok(), "expected valid path: {path}");
		assert_eq!(result.unwrap().path, Some(path.to_string()));
	}

	#[rstest]
	fn test_with_path_rejects_empty() {
		// Act
		let result = AppConfig::new("myapp", "myapp").with_path("");

		// Assert
		let err = result.unwrap_err();
		assert!(err.to_string().contains("cannot be empty"));
	}

	#[rstest]
	#[case("../etc/passwd")]
	#[case("apps/../../../etc/shadow")]
	#[case("apps/..")]
	fn test_with_path_rejects_traversal(#[case] path: &str) {
		// Act
		let result = AppConfig::new("myapp", "myapp").with_path(path);

		// Assert
		let err = result.unwrap_err();
		assert!(
			err.to_string().contains("path traversal"),
			"expected traversal error for '{path}', got: {err}"
		);
	}

	#[rstest]
	#[case("/etc/passwd")]
	#[case("/absolute/path")]
	#[case("\\windows\\path")]
	#[case("C:\\Windows\\System32")]
	#[case("D:/data")]
	fn test_with_path_rejects_absolute(#[case] path: &str) {
		// Act
		let result = AppConfig::new("myapp", "myapp").with_path(path);

		// Assert
		let err = result.unwrap_err();
		assert!(
			err.to_string().contains("relative, not absolute"),
			"expected absolute path error for '{path}', got: {err}"
		);
	}

	#[rstest]
	fn test_with_path_rejects_null_bytes() {
		// Act
		let result = AppConfig::new("myapp", "myapp").with_path("apps/my\0app");

		// Assert
		let err = result.unwrap_err();
		assert!(err.to_string().contains("null bytes"));
	}

	#[rstest]
	#[case("apps/my\napp")]
	#[case("apps/my\rapp")]
	fn test_with_path_rejects_control_chars(#[case] path: &str) {
		// Act
		let result = AppConfig::new("myapp", "myapp").with_path(path);

		// Assert
		let err = result.unwrap_err();
		assert!(
			err.to_string().contains("control characters"),
			"expected control char error for path, got: {err}"
		);
	}
}

// ============================================================================
// Type-safe application registry (compile-time checked)
// ============================================================================

/// Trait for applications that can be accessed at compile time
///
/// Implement this trait for each application in your project.
/// The compiler will ensure that only valid application labels can be used.
///
/// # Example
///
/// ```rust
/// use reinhardt_apps::apps::AppLabel;
///
/// pub struct AuthApp;
/// impl AppLabel for AuthApp {
///     const LABEL: &'static str = "auth";
/// }
/// ```
///
/// # Enum-Style Implementors
///
/// `AppLabel` can also be implemented on enums where each variant maps
/// to a different label. In that case, declare [`LABEL`](AppLabel::LABEL)
/// as `""` explicitly (the trait intentionally has no default, so the
/// compiler enforces that you make a choice) and override
/// [`path`](AppLabel::path) to dispatch on `self`. The `installed_apps!`
/// macro uses this pattern for the generated `InstalledApp` enum.
///
/// ```
/// use reinhardt_apps::apps::AppLabel;
///
/// #[derive(Clone, Copy)]
/// enum MyApps {
///     Auth,
///     Blog,
/// }
///
/// impl AppLabel for MyApps {
///     const LABEL: &'static str = "";
///
///     fn path(&self) -> &'static str {
///         match self {
///             MyApps::Auth => "auth",
///             MyApps::Blog => "blog",
///         }
///     }
/// }
///
/// assert_eq!(MyApps::Auth.path(), "auth");
/// assert_eq!(MyApps::Blog.path(), "blog");
/// ```
pub trait AppLabel {
	/// The unique label for this application when the implementor is a
	/// type-level marker (unit struct). Enum-style implementors that
	/// dispatch on `self` via [`path`](AppLabel::path) should still
	/// declare `const LABEL: &'static str = "";` explicitly; the trait
	/// intentionally has no default so that forgetting both `LABEL` *and*
	/// a `path()` override fails at compile time rather than silently
	/// producing an empty label at runtime.
	const LABEL: &'static str;

	/// Returns the registered path/label string for this specific value.
	///
	/// Default implementation returns [`LABEL`](AppLabel::LABEL), which
	/// is the correct behavior for type-level marker implementors. Enum
	/// implementors must override this method to dispatch on `self`.
	fn path(&self) -> &'static str {
		Self::LABEL
	}
}

impl Apps {
	/// Type-safe get_app_config method
	///
	/// This method ensures at compile time that only valid application types
	/// can be used.
	///
	/// # Example
	///
	/// ```rust
	/// use reinhardt_apps::apps::{Apps, AppLabel};
	///
	/// pub struct AuthApp;
	/// impl AppLabel for AuthApp {
	///     const LABEL: &'static str = "auth";
	/// }
	///
	/// let apps = Apps::new(vec!["auth".to_string()]);
	/// // This will compile because AuthApp implements AppLabel
	/// let result = apps.get_app_config_typed::<AuthApp>();
	/// ```
	pub fn get_app_config_typed<A: AppLabel>(&self) -> AppResult<AppConfig> {
		self.get_app_config(A::LABEL)
	}

	/// Type-safe check if an application is installed
	///
	/// # Example
	///
	/// ```rust
	/// use reinhardt_apps::apps::{Apps, AppLabel};
	///
	/// pub struct AuthApp;
	/// impl AppLabel for AuthApp {
	///     const LABEL: &'static str = "auth";
	/// }
	///
	/// let apps = Apps::new(vec!["auth".to_string()]);
	/// assert!(apps.is_installed_typed::<AuthApp>());
	/// ```
	pub fn is_installed_typed<A: AppLabel>(&self) -> bool {
		self.is_installed(A::LABEL)
	}
}

#[cfg(test)]
mod typed_tests {
	use super::*;

	// Test application types
	struct AuthApp;
	impl AppLabel for AuthApp {
		const LABEL: &'static str = "auth";
	}

	struct ContentTypesApp;
	impl AppLabel for ContentTypesApp {
		const LABEL: &'static str = "contenttypes";
	}

	struct SessionsApp;
	impl AppLabel for SessionsApp {
		const LABEL: &'static str = "sessions";
	}

	#[test]
	fn test_typed_is_installed() {
		let apps = Apps::new(vec!["auth".to_string(), "contenttypes".to_string()]);

		assert!(apps.is_installed_typed::<AuthApp>());
		assert!(apps.is_installed_typed::<ContentTypesApp>());
		assert!(!apps.is_installed_typed::<SessionsApp>());
	}

	#[test]
	fn test_typed_get_app_config() {
		let apps = Apps::new(vec![]);
		let config = AppConfig::new("auth", "auth");
		apps.register(config).unwrap();

		let retrieved = apps.get_app_config_typed::<AuthApp>();
		assert!(retrieved.is_ok());
		assert_eq!(retrieved.unwrap().label, "auth");
	}

	#[test]
	fn test_typed_get_app_config_not_found() {
		let apps = Apps::new(vec![]);

		let result = apps.get_app_config_typed::<SessionsApp>();
		assert!(result.is_err());

		if let Err(AppError::NotFound(label)) = result {
			assert_eq!(label, "sessions");
		}
	}

	#[test]
	fn test_apps_typed_and_regular_mixed() {
		let apps = Apps::new(vec!["auth".to_string()]);
		let config = AppConfig::new("auth", "auth");
		apps.register(config).unwrap();

		// Can use both typed and regular methods
		assert!(apps.is_installed_typed::<AuthApp>());
		assert!(apps.is_installed("auth"));

		let typed = apps.get_app_config_typed::<AuthApp>().unwrap();
		let regular = apps.get_app_config("auth").unwrap();

		assert_eq!(typed.label, regular.label);
	}
}

// ============================================================================
// Global Registry (inventory-based)
//
// The items below use `inventory::collect!`, which relies on link-section
// constructors that are not portable to `wasm32-unknown-unknown`. They model
// server-side discovery of static files / locales / commands / media files,
// none of which are meaningful on the wasm client target, so they are
// `#[cfg(native)]`-gated individually.
// ============================================================================

/// Base trait for custom management commands
///
/// Applications can implement this trait to provide custom commands
/// that will be automatically discovered by the manage.py CLI.
#[cfg(native)]
pub trait BaseCommand: Send + Sync {
	/// Command name (e.g., "createsuperuser")
	fn name(&self) -> &str;

	/// Command help text
	fn help(&self) -> &str;

	/// Execute the command
	fn execute(&mut self, args: Vec<String>) -> Result<(), Box<dyn std::error::Error>>;
}

/// Static files configuration from an app
///
/// Applications can register their static files directories using this struct.
/// Registered configurations will be automatically discovered by collectstatic.
/// Uses static string references for compile-time registration.
#[cfg(native)]
pub struct AppStaticFilesConfig {
	/// Application label that owns these static files.
	pub app_label: &'static str,
	/// Filesystem path to the static files directory.
	pub static_dir: &'static str,
	/// URL prefix under which the static files are served.
	pub url_prefix: &'static str,
}

#[cfg(native)]
inventory::collect!(AppStaticFilesConfig);

/// Locale configuration from an app
///
/// Applications can register their locale directories using this struct.
/// Registered configurations will be automatically discovered by makemessages.
/// Uses static string references for compile-time registration.
#[cfg(native)]
pub struct AppLocaleConfig {
	/// Application label that owns these locale files.
	pub app_label: &'static str,
	/// Filesystem path to the locale directory.
	pub locale_dir: &'static str,
}

#[cfg(native)]
inventory::collect!(AppLocaleConfig);

/// Command configuration from an app
///
/// Applications can register their custom management commands using this struct.
/// Registered commands will be automatically discovered by the manage.py CLI.
/// Uses static string references for compile-time registration.
#[cfg(native)]
pub struct AppCommandConfig {
	/// Application label that owns this command.
	pub app_label: &'static str,
	/// Name of the management command.
	pub command_name: &'static str,
	/// Factory function that creates the command instance.
	pub command_fn: fn() -> Box<dyn BaseCommand>,
}

#[cfg(native)]
inventory::collect!(AppCommandConfig);

/// Media files configuration from an app
///
/// Applications can register their media files directories using this struct.
/// Registered configurations will be automatically discovered by collectmedia.
/// Uses static string references for compile-time registration.
#[cfg(native)]
pub struct AppMediaConfig {
	/// Application label that owns these media files.
	pub app_label: &'static str,
	/// Filesystem path to the media files directory.
	pub media_dir: &'static str,
	/// URL prefix under which the media files are served.
	pub url_prefix: &'static str,
}

#[cfg(native)]
inventory::collect!(AppMediaConfig);

// ============================================================================
// Registration Macros
//
// These macros expand to `$crate::inventory::submit!` blocks that reference
// native-only types (`AppStaticFilesConfig`, `AppLocaleConfig`, etc.) and the
// native-only `inventory` re-export. They are therefore `#[cfg(native)]`-gated
// individually and not exported on `wasm32-unknown-unknown`.
// ============================================================================

/// Register static files for an application
///
/// # Example
///
/// ```rust,ignore
/// use reinhardt_apps::register_app_static_files;
/// use std::path::PathBuf;
///
/// register_app_static_files!(
///     "myapp",
///     PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("static"),
///     "/static/myapp/"
/// );
/// ```
#[cfg(native)]
#[macro_export]
macro_rules! register_app_static_files {
	($app_label:expr, $static_dir:expr, $url_prefix:expr) => {
		$crate::inventory::submit! {
			$crate::AppStaticFilesConfig {
				app_label: $app_label,
				static_dir: $static_dir,
				url_prefix: $url_prefix,
			}
		}
	};
}

/// Register locale directory for an application
///
/// # Example
///
/// ```rust,ignore
/// use reinhardt_apps::register_app_locale;
/// use std::path::PathBuf;
///
/// register_app_locale!(
///     "myapp",
///     PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("locale")
/// );
/// ```
#[cfg(native)]
#[macro_export]
macro_rules! register_app_locale {
	($app_label:expr, $locale_dir:expr) => {
		$crate::inventory::submit! {
			$crate::AppLocaleConfig {
				app_label: $app_label,
				locale_dir: $locale_dir,
			}
		}
	};
}

/// Register a custom management command
///
/// # Example
///
/// ```rust,ignore
/// use reinhardt_apps::{register_app_command, BaseCommand};
///
/// struct MyCommand;
/// impl BaseCommand for MyCommand {
///     fn name(&self) -> &str { "mycommand" }
///     fn help(&self) -> &str { "My custom command" }
///     fn execute(&mut self, args: Vec<String>) -> Result<(), Box<dyn std::error::Error>> {
///         Ok(())
///     }
/// }
///
/// register_app_command!(
///     "myapp",
///     "mycommand",
///     || Box::new(MyCommand)
/// );
/// ```
#[cfg(native)]
#[macro_export]
macro_rules! register_app_command {
	($app_label:expr, $command_name:expr, $command_fn:expr) => {
		$crate::inventory::submit! {
			$crate::AppCommandConfig {
				app_label: $app_label,
				command_name: $command_name,
				command_fn: $command_fn,
			}
		}
	};
}

/// Register media files directory for an application
///
/// # Example
///
/// ```rust,ignore
/// use reinhardt_apps::register_app_media;
/// use std::path::PathBuf;
///
/// register_app_media!(
///     "myapp",
///     PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("media"),
///     "/media/myapp/"
/// );
/// ```
#[cfg(native)]
#[macro_export]
macro_rules! register_app_media {
	($app_label:expr, $media_dir:expr, $url_prefix:expr) => {
		$crate::inventory::submit! {
			$crate::AppMediaConfig {
				app_label: $app_label,
				media_dir: $media_dir,
				url_prefix: $url_prefix,
			}
		}
	};
}

// ============================================================================
// Getter Functions
// ============================================================================

/// Get all registered static files configurations
///
/// Returns all static files configurations that have been registered via
/// `register_app_static_files!` macro.
///
/// # Example
///
/// ```rust
/// use reinhardt_apps::get_app_static_files;
///
/// let configs = get_app_static_files();
/// for config in configs {
///     println!("App: {}, Dir: {}", config.app_label, config.static_dir);
/// }
/// ```
#[cfg(native)]
pub fn get_app_static_files() -> Vec<&'static AppStaticFilesConfig> {
	inventory::iter::<AppStaticFilesConfig>().collect()
}

/// Get all registered locale configurations
///
/// Returns all locale configurations that have been registered via
/// `register_app_locale!` macro.
///
/// # Example
///
/// ```rust
/// use reinhardt_apps::get_app_locales;
///
/// let configs = get_app_locales();
/// for config in configs {
///     println!("App: {}, Dir: {}", config.app_label, config.locale_dir);
/// }
/// ```
#[cfg(native)]
pub fn get_app_locales() -> Vec<&'static AppLocaleConfig> {
	inventory::iter::<AppLocaleConfig>().collect()
}

/// Get all registered command configurations
///
/// Returns all command configurations that have been registered via
/// `register_app_command!` macro.
///
/// # Example
///
/// ```rust
/// use reinhardt_apps::get_app_commands;
///
/// let configs = get_app_commands();
/// for config in configs {
///     println!("App: {}, Command: {}", config.app_label, config.command_name);
/// }
/// ```
#[cfg(native)]
pub fn get_app_commands() -> Vec<&'static AppCommandConfig> {
	inventory::iter::<AppCommandConfig>().collect()
}

/// Get all registered media configurations
///
/// Returns all media configurations that have been registered via
/// `register_app_media!` macro.
///
/// # Example
///
/// ```rust
/// use reinhardt_apps::get_app_media;
///
/// let configs = get_app_media();
/// for config in configs {
///     println!("App: {}, Dir: {}", config.app_label, config.media_dir);
/// }
/// ```
#[cfg(native)]
pub fn get_app_media() -> Vec<&'static AppMediaConfig> {
	inventory::iter::<AppMediaConfig>().collect()
}