//! OGG Vorbis deobfuscation for [`ScdFormat::OggVorbis`] tracks.
//!
//! Historical FFXIV OGG tracks were XOR-obfuscated to prevent trivial extraction.  Two
//! obfuscation versions exist:
//!
//! - **Version 2** — simple single-byte XOR over the OGG header region.  Modern game data
//!   (7.x) no longer applies this; the decoder sniffs for `OggS` magic and passes through
//!   unmodified when the header is already valid.
//! - **Version 3** — full-payload XOR keyed by body size, using [`OGG_XOR_TABLE`].
//!
//! Entry point: [`deobfuscate`].

use crate::error::{Error, Result};
use crate::scd::track::OggVorbisSeekTableHeader;

/// Position-dependent XOR table used by the version-3 obfuscation scheme.
pub(super) const OGG_XOR_TABLE: [u8; 256] = [
    0x3A, 0x32, 0x32, 0x32, 0x03, 0x7E, 0x12, 0xF7, 0xB2, 0xE2, 0xA2, 0x67, 0x32, 0x32, 0x22, 0x32,
    0x32, 0x52, 0x16, 0x1B, 0x3C, 0xA1, 0x54, 0x7B, 0x1B, 0x97, 0xA6, 0x93, 0x1A, 0x4B, 0xAA, 0xA6,
    0x7A, 0x7B, 0x1B, 0x97, 0xA6, 0xF7, 0x02, 0xBB, 0xAA, 0xA6, 0xBB, 0xF7, 0x2A, 0x51, 0xBE, 0x03,
    0xF4, 0x2A, 0x51, 0xBE, 0x03, 0xF4, 0x2A, 0x51, 0xBE, 0x12, 0x06, 0x56, 0x27, 0x32, 0x32, 0x36,
    0x32, 0xB2, 0x1A, 0x3B, 0xBC, 0x91, 0xD4, 0x7B, 0x58, 0xFC, 0x0B, 0x55, 0x2A, 0x15, 0xBC, 0x40,
    0x92, 0x0B, 0x5B, 0x7C, 0x0A, 0x95, 0x12, 0x35, 0xB8, 0x63, 0xD2, 0x0B, 0x3B, 0xF0, 0xC7, 0x14,
    0x51, 0x5C, 0x94, 0x86, 0x94, 0x59, 0x5C, 0xFC, 0x1B, 0x17, 0x3A, 0x3F, 0x6B, 0x37, 0x32, 0x32,
    0x30, 0x32, 0x72, 0x7A, 0x13, 0xB7, 0x26, 0x60, 0x7A, 0x13, 0xB7, 0x26, 0x50, 0xBA, 0x13, 0xB4,
    0x2A, 0x50, 0xBA, 0x13, 0xB5, 0x2E, 0x40, 0xFA, 0x13, 0x95, 0xAE, 0x40, 0x38, 0x18, 0x9A, 0x92,
    0xB0, 0x38, 0x00, 0xFA, 0x12, 0xB1, 0x7E, 0x00, 0xDB, 0x96, 0xA1, 0x7C, 0x08, 0xDB, 0x9A, 0x91,
    0xBC, 0x08, 0xD8, 0x1A, 0x86, 0xE2, 0x70, 0x39, 0x1F, 0x86, 0xE0, 0x78, 0x7E, 0x03, 0xE7, 0x64,
    0x51, 0x9C, 0x8F, 0x34, 0x6F, 0x4E, 0x41, 0xFC, 0x0B, 0xD5, 0xAE, 0x41, 0xFC, 0x0B, 0xD5, 0xAE,
    0x41, 0xFC, 0x3B, 0x70, 0x71, 0x64, 0x33, 0x32, 0x12, 0x32, 0x32, 0x36, 0x70, 0x34, 0x2B, 0x56,
    0x22, 0x70, 0x3A, 0x13, 0xB7, 0x26, 0x60, 0xBA, 0x1B, 0x94, 0xAA, 0x40, 0x38, 0x00, 0xFA, 0xB2,
    0xE2, 0xA2, 0x67, 0x32, 0x32, 0x12, 0x32, 0xB2, 0x32, 0x32, 0x32, 0x32, 0x75, 0xA3, 0x26, 0x7B,
    0x83, 0x26, 0xF9, 0x83, 0x2E, 0xFF, 0xE3, 0x16, 0x7D, 0xC0, 0x1E, 0x63, 0x21, 0x07, 0xE3, 0x01,
];

/// Deobfuscates an OGG Vorbis payload, returning a clean OGG byte stream.
///
/// Behaviour depends on [`OggVorbisSeekTableHeader::version`]:
///
/// - **Version 2**: if `raw` already starts with `OggS`, returns a copy unchanged (modern
///   passthrough).  Otherwise XORs the first `ogg_header_size` bytes with `xor_byte`.
/// - **Version 3**: XORs every byte using a position-dependent key derived from
///   [`OGG_XOR_TABLE`] and the low 7 bits of the body size.
/// - **Other versions**: returns a copy unchanged.
///
/// Returns [`Error::InvalidOggHeader`] if `ogg_header_size` exceeds `raw.len()`.
pub(crate) fn deobfuscate(header: &OggVorbisSeekTableHeader, raw: &[u8]) -> Result<Vec<u8>> {
    let ogg_header_size =
        usize::try_from(header.ogg_header_size).map_err(|_| Error::InvalidOggHeader {
            reason: "ogg_header_size does not fit usize",
        })?;
    if ogg_header_size > raw.len() {
        return Err(Error::InvalidOggHeader {
            reason: "ogg_header_size exceeds raw payload window",
        });
    }

    let mut out = raw.to_vec();
    let total = out.len();
    let body_size = total - ogg_header_size;

    match header.version {
        2 => {
            if raw.len() >= 4 && &raw[..4] == b"OggS" {
                return Ok(out);
            }
            let mask = header.xor_byte;
            for b in &mut out[..ogg_header_size] {
                *b ^= mask;
            }
        }
        3 => {
            #[allow(clippy::cast_possible_truncation)]
            let body_low = (body_size & 0x7F) as u8;
            let seed_lo = body_low & 0x3F;
            for (j, b) in out.iter_mut().enumerate() {
                #[allow(clippy::cast_possible_truncation)]
                let j_low = (j & 0xFF) as u8;
                let idx = seed_lo.wrapping_add(j_low);
                let table_byte = OGG_XOR_TABLE[idx as usize];
                *b = table_byte ^ *b ^ body_low;
            }
        }
        _ => {}
    }

    Ok(out)
}
