//! Linear-film receipt — a JWP profile, the worlds/splat4d receipt
//! transposed to film. The **film hash** is the identity (contract + world +
//! camera); the group's objects are the per-frame reconstruction blocks
//! (each `frame_hash` = world state hash at the frame's tick, bound to the
//! interpolated camera pose), Merkle-bound with JWP's exact domains; one
//! Ed25519 signature covers a profile payload carrying film hash + frame
//! hashes + exact reconstruction work + measured joules. Chains via
//! `parent_receipt_hash` exactly as the others — reuse, not reinvention.

use super::Film;
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:film-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 FilmReceipt {
    pub film_hash: [u8; 32],
    pub group_id: u64,
    pub frames: Vec<FrameHash>,
    pub merkle_root: [u8; 32],
    /// Exact, deterministic reconstruction work = number of frames sampled.
    pub work_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 FilmReceipt {
    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.film_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_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>,
        film_hash: [u8; 32],
        group_id: u64,
        frames: Vec<FrameHash>,
        work_frames: u64,
        joules_micro: u64,
        parent_receipt_hash: Option<[u8; 32]>,
    ) -> FilmReceipt {
        let leaves: Vec<[u8; 32]> = frames.iter().map(|b| b.hash).collect();
        let mut r = FilmReceipt {
            film_hash,
            group_id,
            frames,
            merkle_root: merkle_root(&leaves),
            work_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<FilmReceipt, 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:film-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\":\"linear-film\",\"film_hash\":\"{}\",\"frame_hashes\":[{}],\"group_id\":{},\"joules_micro\":{},\"leaf_count\":{},\"parent_receipt_hash\":{},\"receipt_hash\":\"{}\",\"root_hash\":\"{}\",\"sig\":\"{}\",\"signer_id\":{},\"signer_pubkey\":\"{}\",\"work_frames\":{}}}",
            hx(&self.film_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_frames,
        );
        json_with_label(json, self.energy_provenance.as_ref())
    }
}

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

    fn key(s: u8) -> SigningKey {
        SigningKey::from_bytes(&[s; 32])
    }

    fn frames() -> Vec<FrameHash> {
        (0..5u64).map(|i| FrameHash { index: i, hash: [i as u8 + 1; 32] }).collect()
    }

    #[test]
    fn receipt_commits_verifies_and_tamper_fails() {
        let r = FilmReceipt::build(&key(9), "did:web:wai#film", [0xab; 32], 0, frames(), 5, 8080, 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 fh = [0xcd; 32];
        let r0 = FilmReceipt::build(&key(9), "id", fh, 0, frames(), 5, 0, None);
        let r1 = FilmReceipt::build(&key(9), "id", fh, 1, frames(), 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 r = FilmReceipt::build(&key(9), "did:web:wai#film", [0xab; 32], 0, frames(), 5, 8080, None);
        crate::sig::assert_refuses_forgeries(&r, |r, k, s| (r.signer_pubkey, r.sig) = (k, s), |r| r.signing_payload(), |r| r.verify());
    }
}

impl Film {
    /// Build a film receipt over this film's per-frame reconstruction blocks.
    /// `joules_micro` is supplied by the meter; `0` is the unmetered marker,
    /// never a figure of zero joules (energy-measurement §2).
    pub fn receipt(
        &self,
        signer: &SigningKey,
        signer_id: impl Into<String>,
        group_id: u64,
        joules_micro: u64,
        parent_receipt_hash: Option<[u8; 32]>,
    ) -> Result<FilmReceipt, super::FilmError> {
        let frames = self.frame_hashes()?;
        let work = frames.len() as u64;
        Ok(FilmReceipt::build(
            signer,
            signer_id,
            self.film_hash(),
            group_id,
            frames,
            work,
            joules_micro,
            parent_receipt_hash,
        ))
    }
}
