//! 4D-splat clip receipt — a JWP profile, the worlds/audio/haptic receipt
//! transposed to volumetric. The **clip hash** is the identity; the
//! group's objects are the per-frame reconstruction blocks (each frame's
//! `frame_hash`), Merkle-bound with JWP's exact domains; one Ed25519
//! signature covers a profile payload carrying clip hash + frame hashes +
//! exact reconstruction work + measured joules. Chains via
//! `parent_receipt_hash` exactly as the others.

use super::Splat4dClipData;
use crate::world::receipt::merkle_root;
use crate::energy_class::{
    check_label, json_with_label, label_coheres, labelled_domain, write_label, AcquisitionError,
    EnergyProvenance,
};
use ed25519_dalek::{Signer, SigningKey};

const DOMAIN_RECEIPT: &[u8] = b"wai:splat4d-receipt\x01";

/// `(frame_index, the frame's BLAKE3 reconstruction hash)`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct FrameHash {
    pub index: u64,
    pub hash: [u8; 32],
}

#[derive(Clone, Debug, PartialEq)]
pub struct Splat4dReceipt {
    pub clip_hash: [u8; 32],
    pub group_id: u64,
    pub frames: Vec<FrameHash>,
    pub merkle_root: [u8; 32],
    /// Exact, deterministic reconstruction work = frames × Gaussians.
    pub work_gaussian_frames: u64,
    /// Carried microjoules (native meter supplies; 0 = unmetered).
    pub joules_micro: u64,
    /// How `joules_micro` was acquired — an optional label
    /// (`extensions/energy-measurement.md` §2.8). `None` is an unlabelled
    /// figure, as every receipt sealed before the label existed carries; it is
    /// never read as any class. Inside the signature when present.
    pub energy_provenance: Option<EnergyProvenance>,
    pub parent_receipt_hash: Option<[u8; 32]>,
    pub signer_pubkey: [u8; 32],
    pub signer_id: String,
    pub sig: [u8; 64],
}

impl Splat4dClipData {
    /// Per-frame reconstruction-block hashes — the receipt's objects.
    pub fn frame_hashes(&self) -> Vec<FrameHash> {
        (0..self.contract.n_frames)
            .map(|f| FrameHash { index: f, hash: self.frame_hash(f) })
            .collect()
    }
}

impl Splat4dReceipt {
    fn signing_payload(&self) -> Vec<u8> {
        let label = self.energy_provenance.as_ref();
        let mut o = labelled_domain(DOMAIN_RECEIPT, label);
        o.extend_from_slice(&self.clip_hash);
        o.extend_from_slice(&self.group_id.to_be_bytes());
        o.extend_from_slice(&self.merkle_root);
        o.extend_from_slice(&(self.frames.len() as u64).to_be_bytes());
        o.extend_from_slice(&self.work_gaussian_frames.to_be_bytes());
        o.extend_from_slice(&self.joules_micro.to_be_bytes());
        write_label(label, &mut o);
        match self.parent_receipt_hash {
            Some(h) => {
                o.push(1);
                o.extend_from_slice(&h);
            }
            None => o.push(0),
        }
        for b in &self.frames {
            o.extend_from_slice(&b.index.to_be_bytes());
            o.extend_from_slice(&b.hash);
        }
        o.extend_from_slice(&self.signer_pubkey);
        let id = self.signer_id.as_bytes();
        o.extend_from_slice(&(id.len() as u32).to_be_bytes());
        o.extend_from_slice(id);
        o
    }

    #[allow(clippy::too_many_arguments)]
    pub fn build(
        signer: &SigningKey,
        signer_id: impl Into<String>,
        clip_hash: [u8; 32],
        group_id: u64,
        frames: Vec<FrameHash>,
        work_gaussian_frames: u64,
        joules_micro: u64,
        parent_receipt_hash: Option<[u8; 32]>,
    ) -> Splat4dReceipt {
        let leaves: Vec<[u8; 32]> = frames.iter().map(|b| b.hash).collect();
        let mut r = Splat4dReceipt {
            clip_hash,
            group_id,
            frames,
            merkle_root: merkle_root(&leaves),
            work_gaussian_frames,
            joules_micro,
            energy_provenance: None,
            parent_receipt_hash,
            signer_pubkey: signer.verifying_key().to_bytes(),
            signer_id: signer_id.into(),
            sig: [0u8; 64],
        };
        r.sig = signer.sign(&r.signing_payload()).to_bytes();
        r
    }

    pub fn verify(&self) -> bool {
        if !label_coheres(self.joules_micro, self.energy_provenance.as_ref()) {
            return false;
        }
        let leaves: Vec<[u8; 32]> = self.frames.iter().map(|b| b.hash).collect();
        if merkle_root(&leaves) != self.merkle_root {
            return false;
        }
        crate::sig::verify_strict(&self.signer_pubkey, &self.signing_payload(), &self.sig).is_ok()
    }

    /// Label the figure with its acquisition class and re-sign
    /// (`extensions/energy-measurement.md` §2.8). `signer` must be the key
    /// that sealed the receipt. Refuses whatever [`Self::verify`] would
    /// refuse: legacy `HwShunt`, a class beside a zero figure, a refined class
    /// without its evidence.
    pub fn with_energy_class(
        mut self,
        signer: &SigningKey,
        class: EnergyProvenance,
    ) -> Result<Splat4dReceipt, AcquisitionError> {
        if signer.verifying_key().to_bytes() != self.signer_pubkey {
            return Err(AcquisitionError::SignerMismatch);
        }
        check_label(self.joules_micro, Some(&class))?;
        self.energy_provenance = Some(class);
        self.sig = signer.sign(&self.signing_payload()).to_bytes();
        Ok(self)
    }

    /// Re-sign whatever the fields now say, bypassing every check — so tests
    /// can present `verify()` with a correctly signed receipt that breaks a
    /// label rule, and see the rule itself refuse it.
    #[cfg(test)]
    pub(crate) fn resign_for_test(&mut self, signer: &SigningKey) {
        self.sig = signer.sign(&self.signing_payload()).to_bytes();
    }

    pub fn receipt_hash(&self) -> [u8; 32] {
        let mut h = blake3::Hasher::new();
        h.update(b"wai:splat4d-receipt-id\x01");
        h.update(&self.signing_payload());
        h.update(&self.sig);
        *h.finalize().as_bytes()
    }

    pub fn to_json(&self) -> String {
        let hx = |b: &[u8]| b.iter().map(|x| format!("{x:02x}")).collect::<String>();
        let objs: Vec<String> = self.frames.iter().map(|c| format!("\"{}\"", hx(&c.hash))).collect();
        let parent = match self.parent_receipt_hash {
            Some(h) => format!("\"{}\"", hx(&h)),
            None => "null".into(),
        };
        let json = format!(
            "{{\"kind\":\"splat4d-clip\",\"clip_hash\":\"{}\",\"frame_hashes\":[{}],\"group_id\":{},\"joules_micro\":{},\"leaf_count\":{},\"parent_receipt_hash\":{},\"receipt_hash\":\"{}\",\"root_hash\":\"{}\",\"sig\":\"{}\",\"signer_id\":{},\"signer_pubkey\":\"{}\",\"work_gaussian_frames\":{}}}",
            hx(&self.clip_hash),
            objs.join(","),
            self.group_id,
            self.joules_micro,
            self.frames.len(),
            parent,
            hx(&self.receipt_hash()),
            hx(&self.merkle_root),
            hx(&self.sig),
            serde_json::to_string(&self.signer_id).unwrap(),
            hx(&self.signer_pubkey),
            self.work_gaussian_frames,
        );
        json_with_label(json, self.energy_provenance.as_ref())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::splat4d::{GaussKey, Splat4dContract};
    use crate::world::{Fx, NUMERIC_FIXED64};

    fn key(s: u8) -> SigningKey {
        SigningKey::from_bytes(&[s; 32])
    }
    fn clip() -> Splat4dClipData {
        let track = vec![
            GaussKey { frame: 0, pos: [Fx::ZERO; 3], scale: [Fx::ONE; 3], rot: [Fx::ZERO, Fx::ZERO, Fx::ZERO, Fx::ONE], color: [Fx::ONE, Fx::ZERO, Fx::ZERO], opacity: Fx::ONE },
            GaussKey { frame: 4, pos: [Fx::from_int(1), Fx::ZERO, Fx::ZERO], scale: [Fx::ONE; 3], rot: [Fx::ZERO, Fx::ZERO, Fx::ZERO, Fx::ONE], color: [Fx::ONE, Fx::ZERO, Fx::ZERO], opacity: Fx::ZERO },
        ];
        let c = Splat4dContract { frame_rate: 30, numeric: NUMERIC_FIXED64.into(), n_gaussians: 1, n_frames: 5 };
        Splat4dClipData { contract_bytes: c.to_canonical_json(), contract: c, gaussians: vec![track] }
    }

    #[test]
    fn receipt_commits_verifies_and_tamper_fails() {
        let c = clip();
        let frames = c.frame_hashes();
        assert_eq!(frames.len(), 5);
        let work = c.contract.n_frames * c.contract.n_gaussians as u64;
        let r = Splat4dReceipt::build(&key(9), "did:web:wai#splat4d", c.clip_hash(), 0, frames, work, 9999, None);
        assert!(r.verify());
        let mut bad = r.clone();
        bad.joules_micro += 1;
        assert!(!bad.verify());
        let mut bad2 = r.clone();
        bad2.frames[2].hash[0] ^= 1;
        assert!(!bad2.verify());
        let _: serde_json::Value = serde_json::from_str(&r.to_json()).unwrap();
    }

    #[test]
    fn receipts_chain() {
        let c = clip();
        let ch = c.clip_hash();
        let r0 = Splat4dReceipt::build(&key(9), "id", ch, 0, c.frame_hashes(), 5, 0, None);
        let r1 = Splat4dReceipt::build(&key(9), "id", ch, 1, c.frame_hashes(), 5, 0, Some(r0.receipt_hash()));
        assert!(r0.verify() && r1.verify());
        assert_eq!(r1.parent_receipt_hash, Some(r0.receipt_hash()));
        assert_ne!(r0.receipt_hash(), r1.receipt_hash());
    }

    /// The signature is verified strictly (SPEC §7 *Signatures*): a key of small order, a
    /// non-canonical spelling of one, and an R of small order are each refused, though a
    /// lenient check accepts each.
    #[test]
    fn the_signature_is_verified_strictly() {
        let c = clip();
        let r = Splat4dReceipt::build(&key(9), "did:web:wai#splat4d", c.clip_hash(), 0, c.frame_hashes(), 5, 9999, None);
        crate::sig::assert_refuses_forgeries(&r, |r, k, s| (r.signer_pubkey, r.sig) = (k, s), |r| r.signing_payload(), |r| r.verify());
    }
}
