//! Haptic signal receipt — a JWP profile, the worlds/audio receipt
//! transposed to touch. The **signal hash** is the identity; the group's
//! objects are the per-channel reconstruction blocks (the canonical u8
//! buffers), Merkle-bound with JWP's exact domains; one Ed25519 signature
//! covers a profile payload carrying signal hash + block hashes + exact
//! reconstruction work + measured joules. Chains via `parent_receipt_hash`
//! exactly as the others — reuse, not reinvention.

use super::HapticSignal;
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:haptic-receipt\x01";
const DOMAIN_BLOCK: &[u8] = b"wai:haptic-rblock\x01";

/// `(channel_index, BLAKE3 over the channel's canonical u8 buffer)`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ChannelHash {
    pub index: u64,
    pub hash: [u8; 32],
}

#[derive(Clone, Debug, PartialEq)]
pub struct HapticReceipt {
    pub signal_hash: [u8; 32],
    pub group_id: u64,
    pub channels: Vec<ChannelHash>,
    pub merkle_root: [u8; 32],
    /// Exact, deterministic reconstruction work = samples × channels.
    pub work_samples: 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 HapticSignal {
    /// Per-channel reconstruction-block hashes — the receipt's objects.
    pub fn channel_hashes(&self) -> Vec<ChannelHash> {
        (0..self.channels.len())
            .map(|c| {
                let mut h = blake3::Hasher::new();
                h.update(DOMAIN_BLOCK);
                h.update(&(c as u64).to_le_bytes());
                h.update(&self.reconstruct_channel(c));
                ChannelHash { index: c as u64, hash: *h.finalize().as_bytes() }
            })
            .collect()
    }
}

impl HapticReceipt {
    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.signal_hash);
        o.extend_from_slice(&self.group_id.to_be_bytes());
        o.extend_from_slice(&self.merkle_root);
        o.extend_from_slice(&(self.channels.len() as u64).to_be_bytes());
        o.extend_from_slice(&self.work_samples.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.channels {
            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>,
        signal_hash: [u8; 32],
        group_id: u64,
        channels: Vec<ChannelHash>,
        work_samples: u64,
        joules_micro: u64,
        parent_receipt_hash: Option<[u8; 32]>,
    ) -> HapticReceipt {
        let leaves: Vec<[u8; 32]> = channels.iter().map(|b| b.hash).collect();
        let mut r = HapticReceipt {
            signal_hash,
            group_id,
            channels,
            merkle_root: merkle_root(&leaves),
            work_samples,
            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.channels.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<HapticReceipt, 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:haptic-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.channels.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\":\"haptic-signal\",\"channel_hashes\":[{}],\"group_id\":{},\"joules_micro\":{},\"leaf_count\":{},\"parent_receipt_hash\":{},\"receipt_hash\":\"{}\",\"root_hash\":\"{}\",\"sig\":\"{}\",\"signal_hash\":\"{}\",\"signer_id\":{},\"signer_pubkey\":\"{}\",\"work_samples\":{}}}",
            objs.join(","),
            self.group_id,
            self.joules_micro,
            self.channels.len(),
            parent,
            hx(&self.receipt_hash()),
            hx(&self.merkle_root),
            hx(&self.sig),
            hx(&self.signal_hash),
            serde_json::to_string(&self.signer_id).unwrap(),
            hx(&self.signer_pubkey),
            self.work_samples,
        );
        json_with_label(json, self.energy_provenance.as_ref())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::haptic::{HapticContract, HapticKey, HapticSignal};
    use crate::world::{Fx, NUMERIC_FIXED64};

    fn key(s: u8) -> SigningKey {
        SigningKey::from_bytes(&[s; 32])
    }
    fn sig() -> HapticSignal {
        let c = HapticContract { sample_rate: 1000, numeric: NUMERIC_FIXED64.into(), channels: 1, duration: 100 };
        HapticSignal {
            contract_bytes: c.to_canonical_json(),
            contract: c,
            channels: vec![vec![
                HapticKey { pos_sample: 0, intensity: Fx::ZERO, sharpness: Fx::ZERO },
                HapticKey { pos_sample: 99, intensity: Fx::ONE, sharpness: Fx::ONE },
            ]],
        }
    }

    #[test]
    fn receipt_commits_verifies_and_tamper_fails() {
        let s = sig();
        let ch = s.channel_hashes();
        let work = s.contract.duration * s.contract.channels as u64;
        let r = HapticReceipt::build(&key(9), "did:web:wai#haptic", s.signal_hash(), 0, ch, work, 1234, None);
        assert!(r.verify());
        let mut bad = r.clone();
        bad.joules_micro += 1;
        assert!(!bad.verify());
        let mut bad2 = r.clone();
        bad2.channels[0].hash[0] ^= 1;
        assert!(!bad2.verify());
        // valid JSON
        let _: serde_json::Value = serde_json::from_str(&r.to_json()).unwrap();
    }

    #[test]
    fn receipts_chain() {
        let s = sig();
        let sh = s.signal_hash();
        let r0 = HapticReceipt::build(&key(9), "id", sh, 0, s.channel_hashes(), 100, 0, None);
        let r1 = HapticReceipt::build(&key(9), "id", sh, 1, s.channel_hashes(), 100, 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 s = sig();
        let r = HapticReceipt::build(&key(9), "did:web:wai#haptic", s.signal_hash(), 0, s.channel_hashes(), 100, 1234, None);
        crate::sig::assert_refuses_forgeries(&r, |r, k, s| (r.signer_pubkey, r.sig) = (k, s), |r| r.signing_payload(), |r| r.verify());
    }
}
