//! Registered wire forms for the artifact a [`Prior`](crate::container::Prior)
//! names. Normative text: `extensions/prior-carriage.md`.
//!
//! A `Prior` pins a model's identity by digest. The digest fixes *which bytes*;
//! a declared form fixes *what those bytes are*, so two parties holding the same
//! digest also agree on how to read it. A form is named by a capability string
//! from the registry, so the artifact can travel in a WAI envelope under the same
//! name, and a sink decides whether it can read a form by the same dispatch it
//! uses for payloads.

use super::{CAP_PRIOR_GGUF, CAP_PRIOR_NNC, CAP_PRIOR_SAFETENSORS, CAP_PRIOR_SEALED, CAP_PRIOR_SET, CAP_PRIOR_TREE};

/// Every capability string a `Prior` may declare as its artifact's form.
pub fn prior_forms() -> &'static [&'static str] {
    &[CAP_PRIOR_GGUF, CAP_PRIOR_NNC, CAP_PRIOR_SAFETENSORS, CAP_PRIOR_SEALED, CAP_PRIOR_SET, CAP_PRIOR_TREE]
}

/// Whether `cap` is a registered prior form.
pub fn is_prior_form(cap: &str) -> bool {
    prior_forms().contains(&cap)
}

/// Prior forms whose decode to the tensors a network consumes is **established**
/// to give identical tensors at every conforming reader.
///
/// Five. `wai.prior.set`: reading a set through its listing compares digests and
/// hands the decoder each file's bytes unchanged, so every sink that holds the set
/// reads the same parameters. `wai.prior.safetensors` and `wai.prior.gguf`: a reader that
/// follows prior-carriage §9 finds each tensor's bytes where the file's header puts them
/// and hands them over unchanged, refusing a file whose header could be read two ways (a
/// name twice, overlapping or uncovered bytes), so every such reader reads the same
/// tensors from the same file. `wai.prior.sealed`: opening it under its key is a function of
/// its bytes and the key, its plaintext is checked against the SHA-256 it states, and its inner
/// form is one of the two tensor files or a capability's one file (prior-carriage §18.2), so it
/// hands over the bytes the inner form would. `wai.prior.tree`: every piece is checked against
/// its head and the whole set against the SHA-256 the head states, and its inner form is one of
/// these or a sealed set (prior-carriage §19).
///
/// No coded form is listed. ISO/IEC 15938-17 already has payload types that carry
/// values without quantisation: its 2022 edition lists decoding methods for an
/// integer payload type (`NNR_PT_INT`) and a raw-float payload type
/// (`NNR_PT_RAW_FLOAT`), and a decoding process for an integer weight tensor. What
/// is not established here is whether every conforming decoder reconstructs
/// bit-identical parameter values, from those payload types or from quantisation
/// indices. Decoder conformance is specified in its clause 7 and tested with the
/// bitstreams and procedure of ISO/IEC 15938-18, and neither text was read. That is
/// what would settle it, for the published editions and for any later one; a
/// lossless mode added by an amendment would not settle it by itself. Until a coded
/// form is listed, a `replicate` claim cannot rest on a pin in it (see
/// [`Prior::form_preserves_exactness`](crate::container::Prior::form_preserves_exactness)).
const EXACT_RECONSTRUCTION_FORMS: &[&str] = &[CAP_PRIOR_GGUF, CAP_PRIOR_SAFETENSORS, CAP_PRIOR_SEALED, CAP_PRIOR_SET, CAP_PRIOR_TREE];

/// Whether reading an artifact out of `form` is established to reproduce the
/// same tensors at every conforming reader. `false` for an unregistered form.
pub fn form_reconstruction_is_exact(form: &str) -> bool {
    is_prior_form(form) && EXACT_RECONSTRUCTION_FORMS.contains(&form)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::codecs::{
        capability_license, capability_replicate_class, capability_tier, is_known_capability,
        is_neural_integer_exact, is_royalty_free, FidelityTier, LicenseClass, CAP_HAPTIC_MIHS,
        CAP_IMAGE_PNG, CAP_NEURAL_INT_HYPER, CAP_TENSOR_NNC,
    };
    use crate::container::{
        replicate_is_sound, replicate_prior_refusal, Conditioning, DeterminismClass, Manifest,
        ModelRequirement, Prior, PriorRefusal, Wai,
    };

    #[test]
    fn prior_forms_are_registered_capabilities() {
        assert_eq!(prior_forms(), [CAP_PRIOR_GGUF, CAP_PRIOR_NNC, CAP_PRIOR_SAFETENSORS, CAP_PRIOR_SEALED, CAP_PRIOR_SET, CAP_PRIOR_TREE]);
        for &f in prior_forms() {
            assert!(is_known_capability(f), "{f} must be a registered capability");
        }
        // A payload codec is not a model form, and a general tensor is not a
        // network: neither may stand as a prior's form.
        for not_a_form in [CAP_IMAGE_PNG, CAP_NEURAL_INT_HYPER, CAP_TENSOR_NNC, "wai.prior.nope"] {
            assert!(!is_prior_form(not_a_form), "{not_a_form}");
        }
    }

    #[test]
    fn the_listing_and_the_tensor_files_are_established_exact_and_no_coded_form() {
        assert!(form_reconstruction_is_exact(CAP_PRIOR_SET));
        assert!(form_reconstruction_is_exact(CAP_PRIOR_SAFETENSORS));
        assert!(form_reconstruction_is_exact(CAP_PRIOR_GGUF));
        assert!(form_reconstruction_is_exact(CAP_PRIOR_SEALED));
        assert!(form_reconstruction_is_exact(CAP_PRIOR_TREE));
        assert!(!form_reconstruction_is_exact(CAP_PRIOR_NNC));
        assert!(!form_reconstruction_is_exact("wai.prior.nope"));
    }

    #[test]
    fn nnc_capabilities_are_classified_conservatively() {
        for c in [CAP_PRIOR_NNC, CAP_TENSOR_NNC] {
            // Lossy by primary role (compression by parameter reduction and
            // quantisation), as AVIF is. The published standard also has integer
            // and raw-float payload types that carry values unquantised, so this
            // is not a claim that every NNC artifact approximates its source.
            assert_eq!(capability_tier(c), Some(FidelityTier::Lossy), "{c}");
            // Royalty status not established (a RAND patent declaration, and no
            // royalty-free commitment found): never presented as royalty-free.
            assert_eq!(capability_license(c), Some(LicenseClass::PatentPool), "{c}");
            assert!(!is_royalty_free(c), "{c}");
            // Not a neural decode WAI runs, so never in the integer-exact class.
            assert!(capability_replicate_class(c).is_some(), "{c}");
            assert!(!is_neural_integer_exact(c), "{c}");
            // Replicate class: the one the registry gives an MPEG standard whose
            // decoder conformance it has not checked, as it gives MPEG-I Haptics.
            // NNC's decoder conformance (ISO/IEC 15938-17 clause 7, tested per
            // ISO/IEC 15938-18) was not read, so NNC takes no class that a checked
            // conformance would justify. Where the registry has one class for every
            // standard codec, that class; where it separates the standard codecs by
            // what their decoder conformance fixes, the unchecked one.
            assert_eq!(capability_replicate_class(c), capability_replicate_class(CAP_HAPTIC_MIHS),
                       "{c} must be classed as a standard whose conformance was not checked");
        }
    }

    /// The declared-form rule is part of [`Prior::is_cross_hardware_exact`], the
    /// predicate every `replicate` check reads, so it holds whichever check runs:
    /// the free function, the envelope's own check, and the reason a strict decoder
    /// reports. The capability is integer-exact, so only the prior can refuse it.
    #[test]
    fn every_replicate_check_applies_the_form_rule() {
        let integer = Prior::new("int_hyper/q4", "ef".repeat(32), "int-rans/p16+int-synth");
        let nnc = integer.clone().with_form(CAP_PRIOR_NNC);
        let envelope = |intent: &str, prior: &Prior| {
            Wai::new(
                Manifest::new("image", intent, ModelRequirement::new(CAP_NEURAL_INT_HYPER),
                              Conditioning::new("int_hyper").with_prior(prior.clone())),
                vec![],
            )
        };
        assert!(is_neural_integer_exact(CAP_NEURAL_INT_HYPER));
        assert_eq!(nnc.determinism_class(), DeterminismClass::IntegerExact);

        // Sound when the artifact is the bytes the digest covers …
        assert!(integer.is_cross_hardware_exact());
        assert!(replicate_is_sound("replicate", Some(&integer)));
        assert!(envelope("replicate", &integer).replicate_is_sound());
        // … and refused by every check once it must be read out of NNC.
        assert!(!nnc.is_cross_hardware_exact());
        assert!(!replicate_is_sound("replicate", Some(&nnc)));
        assert!(!envelope("replicate", &nnc).replicate_is_sound());
        assert_eq!(envelope("replicate", &nnc).replicate_prior_refusal(),
                   Some(PriorRefusal::FormNotExact(CAP_PRIOR_NNC.into())));
        // Only `replicate` is gated.
        assert!(envelope("improve", &nnc).replicate_is_sound());
        // A set-form pin declaring decode-equivalence is sound: the listing form is
        // established exact.
        let set = integer.clone().with_form(CAP_PRIOR_SET);
        assert!(set.is_cross_hardware_exact());
        assert!(envelope("replicate", &set).replicate_is_sound());

        // The yes/no answer and the reason never disagree.
        let floaty = Prior::new("m", "ab".repeat(32), "int-rans/p16+onnx-cpu-f32/1thread");
        let floaty_nnc = floaty.clone().with_form(CAP_PRIOR_NNC);
        let unregistered = integer.clone().with_form("wai.prior.nope");
        let priors = [None, Some(&integer), Some(&nnc), Some(&floaty), Some(&floaty_nnc),
                      Some(&unregistered)];
        for intent in ["replicate", "improve", "create"] {
            for prior in priors {
                assert_eq!(replicate_is_sound(intent, prior),
                           replicate_prior_refusal(intent, prior).is_none(), "{intent} {prior:?}");
            }
        }
    }
}
