nsb 0.1.0

Night-sky background evaluation and observation planning for ground-based astronomy.
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
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Vallés Puig, Ramon
//! Versioned evidence contract for calibrated site profiles.
//!
//! This module defines the machine-readable inputs required before a named site
//! profile can be promoted from a planning preset to a calibrated profile. It
//! deliberately does not perform that promotion: a valid asset is evidence for
//! later scientific review, not proof that review has happened. Site identity is
//! a stable string so observatory-specific catalogs do not need to live here.

#![allow(dead_code)]

use chrono::NaiveDate;
use serde::{Deserialize, Serialize};
use std::collections::BTreeSet;
use std::path::{Component, Path};
use thiserror::Error;

/// Supported schema version for [`SiteCalibrationAsset`].
pub(crate) const SITE_CALIBRATION_ASSET_SCHEMA_VERSION: u32 = 1;

/// Stable string identifier for a site that may receive a dedicated calibration.
///
/// Values are lowercase hyphenated identifiers (for example `ctao-south`). The
/// reserved generic-clear-sky profile cannot be calibrated through this schema.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(transparent)]
pub struct CalibratedSiteId {
    id: String,
}

impl CalibratedSiteId {
    /// Stable identifier used in calibration metadata.
    pub fn as_str(&self) -> &str {
        &self.id
    }

    /// Planning profile identifier conventionally associated with this site.
    ///
    /// Follows the `{site}-planning` naming used by application-layer presets.
    pub fn planning_profile_name(&self) -> String {
        format!("{}-planning", self.id)
    }
}

/// Time and wavelength domain for which a calibration asset is valid.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct SiteCalibrationValidity {
    /// First inclusive UTC date covered by the calibration, formatted `YYYY-MM-DD`.
    pub valid_from: String,
    /// Last inclusive UTC date covered by the calibration, formatted `YYYY-MM-DD`.
    pub valid_through: String,
    /// Inclusive wavelength interval represented by the calibration, in nanometres.
    pub wavelength_nm: [u16; 2],
}

/// Atmospheric parameters and one-sigma uncertainties for a calibrated site.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct AtmosphericSiteCalibration {
    /// Representative site altitude in metres above mean sea level.
    pub representative_altitude_m: f64,
    /// One-sigma uncertainty of the representative altitude in metres.
    pub representative_altitude_uncertainty_m: f64,
    /// Surface pressure in hectopascals.
    pub surface_pressure_hpa: f64,
    /// One-sigma uncertainty of the surface pressure in hectopascals.
    pub surface_pressure_uncertainty_hpa: f64,
    /// Rayleigh scale height in kilometres.
    pub rayleigh_scale_height_km: f64,
    /// One-sigma uncertainty of the Rayleigh scale height in kilometres.
    pub rayleigh_scale_height_uncertainty_km: f64,
    /// Aerosol optical depth referenced at 550 nm.
    pub aerosol_optical_depth_550_nm: f64,
    /// One-sigma uncertainty of the aerosol optical depth at 550 nm.
    pub aerosol_optical_depth_uncertainty_550_nm: f64,
    /// Angstrom exponent used for aerosol wavelength scaling.
    pub angstrom_exponent: f64,
    /// One-sigma uncertainty of the Angstrom exponent.
    pub angstrom_exponent_uncertainty: f64,
}

/// Airglow continuum calibration and its declared temporal treatment.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct AirglowCalibrationEvidence {
    /// Multiplicative continuum scale relative to the referenced template.
    pub continuum_scale: f64,
    /// One-sigma uncertainty of the continuum scale.
    pub continuum_scale_uncertainty: f64,
    /// Whether a temporal or seasonal correction is applied.
    pub temporal_correction_applied: bool,
    /// Stable identifier of the temporal correction model when one is applied.
    pub correction_model: Option<String>,
}

/// Immutable source used to derive or validate a site calibration.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct SiteCalibrationReference {
    /// Stable lowercase identifier for the reference.
    pub id: String,
    /// Repository-relative path to the pinned reference bytes.
    pub path: String,
    /// Lowercase SHA-256 of the referenced bytes.
    pub sha256: String,
    /// Human-readable source and release identification.
    pub source: String,
    /// License or redistribution terms governing the reference.
    pub license: String,
}

/// Versioned, fail-closed evidence package for a site calibration.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct SiteCalibrationAsset {
    /// Schema version, currently `SITE_CALIBRATION_ASSET_SCHEMA_VERSION`.
    pub schema_version: u32,
    /// Stable lowercase identifier for this calibration release.
    pub calibration_id: String,
    /// Site described by the calibration.
    pub site: CalibratedSiteId,
    /// Time and wavelength domain in which the calibration may be used.
    pub validity: SiteCalibrationValidity,
    /// Atmospheric parameters and uncertainties.
    pub atmosphere: AtmosphericSiteCalibration,
    /// Airglow continuum calibration and temporal treatment.
    pub airglow: AirglowCalibrationEvidence,
    /// Immutable references supporting the calibration.
    pub references: Vec<SiteCalibrationReference>,
    /// Explicit scientific or operational limitations.
    #[serde(default)]
    pub limitations: Vec<String>,
}

/// Error returned when a site-calibration asset cannot be parsed or validated.
#[derive(Debug, Clone, PartialEq, Eq, Error)]
#[error("{message}")]
pub struct SiteCalibrationAssetError {
    message: String,
}

impl SiteCalibrationAssetError {
    fn new(message: impl Into<String>) -> Self {
        Self {
            message: message.into(),
        }
    }
}

impl SiteCalibrationAsset {
    /// Parse and validate one strict TOML calibration asset.
    pub fn from_toml_str(input: &str) -> Result<Self, SiteCalibrationAssetError> {
        let asset: Self = toml::from_str(input).map_err(|error| {
            SiteCalibrationAssetError::new(format!("invalid site-calibration TOML: {error}"))
        })?;
        asset.validate()?;
        Ok(asset)
    }

    /// Validate schema, provenance, physical ranges and internal consistency.
    pub fn validate(&self) -> Result<(), SiteCalibrationAssetError> {
        if self.schema_version != SITE_CALIBRATION_ASSET_SCHEMA_VERSION {
            return Err(SiteCalibrationAssetError::new(format!(
                "unsupported site-calibration schema {}",
                self.schema_version
            )));
        }
        validate_identifier(&self.calibration_id, "calibration_id")?;
        validate_identifier(self.site.as_str(), "site")?;
        if self.site.as_str() == "generic-clear-sky" {
            return Err(SiteCalibrationAssetError::new(
                "site must not be the reserved generic-clear-sky profile",
            ));
        }
        self.validate_validity()?;
        self.validate_atmosphere()?;
        self.validate_airglow()?;
        self.validate_references()?;
        validate_nonempty_items(&self.limitations, "limitations")?;
        Ok(())
    }

    fn validate_validity(&self) -> Result<(), SiteCalibrationAssetError> {
        let valid_from = parse_date(&self.validity.valid_from, "validity.valid_from")?;
        let valid_through = parse_date(&self.validity.valid_through, "validity.valid_through")?;
        if valid_from > valid_through {
            return Err(SiteCalibrationAssetError::new(
                "validity.valid_from must not follow validity.valid_through",
            ));
        }
        let [minimum, maximum] = self.validity.wavelength_nm;
        if minimum < 100 || maximum > 3_000 || minimum >= maximum {
            return Err(SiteCalibrationAssetError::new(
                "validity.wavelength_nm must be an increasing interval within 100..=3000 nm",
            ));
        }
        Ok(())
    }

    fn validate_atmosphere(&self) -> Result<(), SiteCalibrationAssetError> {
        let atmosphere = &self.atmosphere;
        validate_range(
            atmosphere.representative_altitude_m,
            0.0,
            10_000.0,
            "atmosphere.representative_altitude_m",
        )?;
        validate_uncertainty(
            atmosphere.representative_altitude_uncertainty_m,
            10_000.0,
            "atmosphere.representative_altitude_uncertainty_m",
        )?;
        validate_range(
            atmosphere.surface_pressure_hpa,
            f64::MIN_POSITIVE,
            1_200.0,
            "atmosphere.surface_pressure_hpa",
        )?;
        validate_uncertainty(
            atmosphere.surface_pressure_uncertainty_hpa,
            atmosphere.surface_pressure_hpa,
            "atmosphere.surface_pressure_uncertainty_hpa",
        )?;
        validate_range(
            atmosphere.rayleigh_scale_height_km,
            f64::MIN_POSITIVE,
            100.0,
            "atmosphere.rayleigh_scale_height_km",
        )?;
        validate_uncertainty(
            atmosphere.rayleigh_scale_height_uncertainty_km,
            atmosphere.rayleigh_scale_height_km,
            "atmosphere.rayleigh_scale_height_uncertainty_km",
        )?;
        validate_range(
            atmosphere.aerosol_optical_depth_550_nm,
            0.0,
            10.0,
            "atmosphere.aerosol_optical_depth_550_nm",
        )?;
        validate_uncertainty(
            atmosphere.aerosol_optical_depth_uncertainty_550_nm,
            10.0,
            "atmosphere.aerosol_optical_depth_uncertainty_550_nm",
        )?;
        validate_range(
            atmosphere.angstrom_exponent,
            0.0,
            10.0,
            "atmosphere.angstrom_exponent",
        )?;
        validate_uncertainty(
            atmosphere.angstrom_exponent_uncertainty,
            10.0,
            "atmosphere.angstrom_exponent_uncertainty",
        )
    }

    fn validate_airglow(&self) -> Result<(), SiteCalibrationAssetError> {
        validate_range(
            self.airglow.continuum_scale,
            f64::MIN_POSITIVE,
            100.0,
            "airglow.continuum_scale",
        )?;
        validate_uncertainty(
            self.airglow.continuum_scale_uncertainty,
            100.0,
            "airglow.continuum_scale_uncertainty",
        )?;
        match (
            self.airglow.temporal_correction_applied,
            self.airglow.correction_model.as_deref(),
        ) {
            (true, Some(model)) if is_stable_identifier(model) => Ok(()),
            (true, _) => Err(SiteCalibrationAssetError::new(
                "airglow.correction_model must be a stable identifier when a correction is applied",
            )),
            (false, None) => Ok(()),
            (false, Some(_)) => Err(SiteCalibrationAssetError::new(
                "airglow.correction_model must be absent when no correction is applied",
            )),
        }
    }

    fn validate_references(&self) -> Result<(), SiteCalibrationAssetError> {
        if self.references.is_empty() {
            return Err(SiteCalibrationAssetError::new(
                "site calibration requires at least one immutable reference",
            ));
        }

        let mut ids = BTreeSet::new();
        let mut paths = BTreeSet::new();
        for reference in &self.references {
            validate_identifier(&reference.id, "references[].id")?;
            validate_reference_path(&reference.path)?;
            validate_sha256(&reference.sha256)?;
            validate_nonempty(&reference.source, "references[].source")?;
            validate_nonempty(&reference.license, "references[].license")?;
            if !ids.insert(reference.id.as_str()) {
                return Err(SiteCalibrationAssetError::new(format!(
                    "duplicate site-calibration reference id {:?}",
                    reference.id
                )));
            }
            if !paths.insert(reference.path.as_str()) {
                return Err(SiteCalibrationAssetError::new(format!(
                    "duplicate site-calibration reference path {:?}",
                    reference.path
                )));
            }
        }
        Ok(())
    }
}

fn parse_date(value: &str, field: &str) -> Result<NaiveDate, SiteCalibrationAssetError> {
    NaiveDate::parse_from_str(value, "%Y-%m-%d").map_err(|_| {
        SiteCalibrationAssetError::new(format!("{field} must use a valid YYYY-MM-DD date"))
    })
}

fn validate_range(
    value: f64,
    minimum: f64,
    maximum: f64,
    field: &str,
) -> Result<(), SiteCalibrationAssetError> {
    if !value.is_finite() || !(minimum..=maximum).contains(&value) {
        return Err(SiteCalibrationAssetError::new(format!(
            "{field} must be finite and within {minimum}..={maximum}"
        )));
    }
    Ok(())
}

fn validate_uncertainty(
    value: f64,
    maximum: f64,
    field: &str,
) -> Result<(), SiteCalibrationAssetError> {
    validate_range(value, 0.0, maximum, field)
}

fn validate_identifier(value: &str, field: &str) -> Result<(), SiteCalibrationAssetError> {
    if !is_stable_identifier(value) {
        return Err(SiteCalibrationAssetError::new(format!(
            "{field} must contain lowercase ASCII letters, digits and single '-' separators"
        )));
    }
    Ok(())
}

fn is_stable_identifier(value: &str) -> bool {
    !value.is_empty()
        && value.split('-').all(|part| {
            !part.is_empty()
                && part
                    .bytes()
                    .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit())
        })
}

fn validate_reference_path(value: &str) -> Result<(), SiteCalibrationAssetError> {
    let path = Path::new(value);
    if value.trim().is_empty()
        || value.contains('\\')
        || value.split('/').any(|component| component.is_empty())
        || path.is_absolute()
        || path.components().any(|component| {
            matches!(
                component,
                Component::Prefix(_)
                    | Component::RootDir
                    | Component::CurDir
                    | Component::ParentDir
            )
        })
    {
        return Err(SiteCalibrationAssetError::new(
            "references[].path must be a normalized repository-relative path",
        ));
    }
    Ok(())
}

fn validate_sha256(value: &str) -> Result<(), SiteCalibrationAssetError> {
    if value.len() != 64
        || !value
            .bytes()
            .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
    {
        return Err(SiteCalibrationAssetError::new(
            "references[].sha256 must be 64 lowercase hexadecimal characters",
        ));
    }
    Ok(())
}

fn validate_nonempty(value: &str, field: &str) -> Result<(), SiteCalibrationAssetError> {
    if value.trim().is_empty() {
        return Err(SiteCalibrationAssetError::new(format!(
            "{field} must not be empty"
        )));
    }
    Ok(())
}

fn validate_nonempty_items(
    values: &[String],
    field: &str,
) -> Result<(), SiteCalibrationAssetError> {
    if values.iter().any(|value| value.trim().is_empty()) {
        return Err(SiteCalibrationAssetError::new(format!(
            "{field} must not contain empty entries"
        )));
    }
    Ok(())
}

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

    const VALID_ASSET: &str = r#"
schema_version = 1
calibration_id = "ctao-south-reference-v1"
site = "ctao-south"
limitations = ["Valid only for the documented clear, moonless reference sample."]

[validity]
valid_from = "2025-01-01"
valid_through = "2025-12-31"
wavelength_nm = [300, 650]

[atmosphere]
representative_altitude_m = 2150.0
representative_altitude_uncertainty_m = 10.0
surface_pressure_hpa = 743.0
surface_pressure_uncertainty_hpa = 5.0
rayleigh_scale_height_km = 8.0
rayleigh_scale_height_uncertainty_km = 0.2
aerosol_optical_depth_550_nm = 0.03
aerosol_optical_depth_uncertainty_550_nm = 0.01
angstrom_exponent = 1.0
angstrom_exponent_uncertainty = 0.2

[airglow]
continuum_scale = 1.05
continuum_scale_uncertainty = 0.10
temporal_correction_applied = false

[[references]]
id = "ctao-south-atmosphere"
path = "site-calibration/ctao-south/atmosphere-v1.csv"
sha256 = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
source = "Documented CTAO-South atmospheric reference release"
license = "Redistribution terms recorded with the reference asset"
"#;

    fn valid_ctao_north_asset() -> String {
        VALID_ASSET
            .replace("ctao-south", "ctao-north")
            .replace("CTAO-South", "CTAO-North")
    }

    #[test]
    fn parses_a_valid_ctao_south_calibration_asset_deterministically() {
        let first = SiteCalibrationAsset::from_toml_str(VALID_ASSET).unwrap();
        let second = SiteCalibrationAsset::from_toml_str(VALID_ASSET).unwrap();

        assert_eq!(first, second);
        assert_eq!(first.schema_version, SITE_CALIBRATION_ASSET_SCHEMA_VERSION);
        assert_eq!(first.site.as_str(), "ctao-south");
        assert_eq!(first.site.planning_profile_name(), "ctao-south-planning");
        assert_eq!(first.references.len(), 1);
    }

    #[test]
    fn parses_a_valid_ctao_north_calibration_asset_deterministically() {
        let input = valid_ctao_north_asset();
        let first = SiteCalibrationAsset::from_toml_str(&input).unwrap();
        let second = SiteCalibrationAsset::from_toml_str(&input).unwrap();

        assert_eq!(first, second);
        assert_eq!(first.site.as_str(), "ctao-north");
        assert_eq!(first.site.planning_profile_name(), "ctao-north-planning");
    }

    #[test]
    fn rejects_unknown_fields_and_generic_fallback_sites() {
        let unknown = VALID_ASSET.replacen(
            "schema_version = 1",
            "schema_version = 1\nunexpected = true",
            1,
        );
        assert!(SiteCalibrationAsset::from_toml_str(&unknown).is_err());

        let generic =
            VALID_ASSET.replacen("site = \"ctao-south\"", "site = \"generic-clear-sky\"", 1);
        assert!(SiteCalibrationAsset::from_toml_str(&generic).is_err());
    }

    #[test]
    fn rejects_unsupported_schema_invalid_dates_and_negative_physical_values() {
        let unsupported = VALID_ASSET.replacen("schema_version = 1", "schema_version = 2", 1);
        assert!(SiteCalibrationAsset::from_toml_str(&unsupported).is_err());

        let invalid_date = VALID_ASSET.replacen("2025-12-31", "2025-02-30", 1);
        assert!(SiteCalibrationAsset::from_toml_str(&invalid_date).is_err());

        let inverted_validity = VALID_ASSET.replacen(
            "valid_from = \"2025-01-01\"",
            "valid_from = \"2026-01-01\"",
            1,
        );
        let inverted_err = SiteCalibrationAsset::from_toml_str(&inverted_validity)
            .expect_err("valid_from after valid_through must fail closed");
        assert_eq!(
            inverted_err.to_string(),
            "validity.valid_from must not follow validity.valid_through"
        );

        let equal_validity = VALID_ASSET
            .replacen(
                "valid_from = \"2025-01-01\"",
                "valid_from = \"2025-06-01\"",
                1,
            )
            .replacen(
                "valid_through = \"2025-12-31\"",
                "valid_through = \"2025-06-01\"",
                1,
            );
        assert!(
            SiteCalibrationAsset::from_toml_str(&equal_validity).is_ok(),
            "inclusive equal validity bounds must remain accepted"
        );

        let negative_altitude = VALID_ASSET.replacen(
            "representative_altitude_m = 2150.0",
            "representative_altitude_m = -1.0",
            1,
        );
        assert!(SiteCalibrationAsset::from_toml_str(&negative_altitude).is_err());

        let negative_pressure = VALID_ASSET.replacen(
            "surface_pressure_hpa = 743.0",
            "surface_pressure_hpa = -1.0",
            1,
        );
        assert!(SiteCalibrationAsset::from_toml_str(&negative_pressure).is_err());

        let negative_angstrom =
            VALID_ASSET.replacen("angstrom_exponent = 1.0", "angstrom_exponent = -1.0", 1);
        assert!(SiteCalibrationAsset::from_toml_str(&negative_angstrom).is_err());
    }

    #[test]
    fn rejects_missing_provenance_bad_checksums_and_unsafe_paths() {
        let missing_source = VALID_ASSET.replacen(
            "source = \"Documented CTAO-South atmospheric reference release\"",
            "source = \"\"",
            1,
        );
        assert!(SiteCalibrationAsset::from_toml_str(&missing_source).is_err());

        let uppercase_checksum = VALID_ASSET.replacen(
            "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
            "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
            1,
        );
        assert!(SiteCalibrationAsset::from_toml_str(&uppercase_checksum).is_err());

        let unsafe_path = VALID_ASSET.replacen(
            "site-calibration/ctao-south/atmosphere-v1.csv",
            "site-calibration/../atmosphere-v1.csv",
            1,
        );
        assert!(SiteCalibrationAsset::from_toml_str(&unsafe_path).is_err());
    }

    #[test]
    fn rejects_wavelength_bounds_bad_identifiers_and_invalid_uncertainties() {
        let low_wavelength =
            VALID_ASSET.replacen("wavelength_nm = [300, 650]", "wavelength_nm = [99, 650]", 1);
        assert!(
            SiteCalibrationAsset::from_toml_str(&low_wavelength).is_err(),
            "wavelength minimum below 100 nm must fail"
        );

        let high_wavelength = VALID_ASSET.replacen(
            "wavelength_nm = [300, 650]",
            "wavelength_nm = [300, 3001]",
            1,
        );
        assert!(
            SiteCalibrationAsset::from_toml_str(&high_wavelength).is_err(),
            "wavelength maximum above 3000 nm must fail"
        );

        let non_increasing = VALID_ASSET.replacen(
            "wavelength_nm = [300, 650]",
            "wavelength_nm = [650, 650]",
            1,
        );
        assert!(
            SiteCalibrationAsset::from_toml_str(&non_increasing).is_err(),
            "non-increasing wavelength interval must fail"
        );

        let edge_wavelength = VALID_ASSET.replacen(
            "wavelength_nm = [300, 650]",
            "wavelength_nm = [100, 3000]",
            1,
        );
        assert!(
            SiteCalibrationAsset::from_toml_str(&edge_wavelength).is_ok(),
            "inclusive 100..=3000 wavelength bounds must remain accepted"
        );

        let bad_calibration_id = VALID_ASSET.replacen(
            "calibration_id = \"ctao-south-reference-v1\"",
            "calibration_id = \"CTA_South\"",
            1,
        );
        assert!(SiteCalibrationAsset::from_toml_str(&bad_calibration_id).is_err());

        let empty_calibration_id = VALID_ASSET.replacen(
            "calibration_id = \"ctao-south-reference-v1\"",
            "calibration_id = \"\"",
            1,
        );
        assert!(SiteCalibrationAsset::from_toml_str(&empty_calibration_id).is_err());

        let double_hyphen_id = VALID_ASSET.replacen(
            "calibration_id = \"ctao-south-reference-v1\"",
            "calibration_id = \"ctao--south\"",
            1,
        );
        assert!(
            SiteCalibrationAsset::from_toml_str(&double_hyphen_id).is_err(),
            "empty identifier segments between hyphens must fail"
        );

        let oversized_uncertainty = VALID_ASSET.replacen(
            "surface_pressure_uncertainty_hpa = 5.0",
            "surface_pressure_uncertainty_hpa = 800.0",
            1,
        );
        assert!(SiteCalibrationAsset::from_toml_str(&oversized_uncertainty).is_err());

        let uncertainty_equal_to_value = VALID_ASSET.replacen(
            "surface_pressure_uncertainty_hpa = 5.0",
            "surface_pressure_uncertainty_hpa = 743.0",
            1,
        );
        assert!(
            SiteCalibrationAsset::from_toml_str(&uncertainty_equal_to_value).is_ok(),
            "uncertainty equal to the parent value remains inclusive"
        );

        let mut bad_model = SiteCalibrationAsset::from_toml_str(VALID_ASSET).unwrap();
        bad_model.airglow.temporal_correction_applied = true;
        bad_model.airglow.correction_model = Some("Not A Stable Id".into());
        assert!(bad_model.validate().is_err());
    }

    #[test]
    fn rejects_duplicate_references_and_inconsistent_temporal_metadata() {
        let mut duplicate = SiteCalibrationAsset::from_toml_str(VALID_ASSET).unwrap();
        duplicate.references.push(duplicate.references[0].clone());
        assert!(duplicate.validate().is_err());

        let mut correction = SiteCalibrationAsset::from_toml_str(VALID_ASSET).unwrap();
        correction.airglow.temporal_correction_applied = true;
        assert!(correction.validate().is_err());
        correction.airglow.correction_model = Some("seasonal-v1".to_string());
        assert!(correction.validate().is_ok());
    }
}