use serde::Serialize;

/// XEX2 file header. Parsed from the beginning of an Xbox 360 executable.
#[derive(Debug, Serialize)]
pub struct Xex2Header {
    pub magic: u32,
    pub module_flags: u32,
    pub header_size: u32,
    pub security_offset: u32,
    pub header_count: u32,
    pub optional_headers: Vec<Xex2OptionalHeader>,
    pub security_info: Option<Xex2SecurityInfo>,
    /// Parsed file format info (if present).
    pub file_format_info: Option<FileFormatInfo>,
    /// Parsed import libraries (addresses only until resolve_imports is called).
    pub import_libraries: Vec<ImportLibrary>,
    /// Execution info (title ID, media ID, etc.).
    pub execution_info: Option<ExecutionInfo>,
    /// Original PE name from the XEX header.
    pub original_pe_name: Option<String>,
}

#[derive(Debug, Serialize)]
pub struct Xex2OptionalHeader {
    pub key: u32,
    pub value: u32,
}

#[derive(Debug, Serialize)]
pub struct Xex2SecurityInfo {
    pub image_size: u32,
    pub load_address: u32,
    pub export_table_address: u32,
    pub image_flags: u32,
    /// Encrypted session key (decrypted with retail/devkit key to get actual session key).
    pub aes_key: [u8; 16],
    pub page_descriptors: Vec<Xex2PageDescriptor>,
}

#[derive(Debug, Clone, Copy, Serialize)]
pub struct Xex2PageDescriptor {
    pub size_and_info: u32,
}

impl Xex2PageDescriptor {
    pub fn page_count(&self) -> u32 {
        self.size_and_info >> 4
    }

    pub fn info(&self) -> u32 {
        self.size_and_info & 0xF
    }
}

/// File format info (compression and encryption types).
#[derive(Debug, Clone, Serialize)]
pub struct FileFormatInfo {
    pub info_size: u32,
    pub encryption_type: u16,
    pub compression_type: u16,
    /// For basic compression: list of (data_size, zero_size) block pairs.
    pub basic_blocks: Vec<BasicCompressionBlock>,
    /// For normal (LZX) compression: window size.
    pub normal_window_size: u32,
    /// For normal (LZX) compression: first block size (from header).
    pub normal_first_block_size: u32,
    /// For normal (LZX) compression: first block hash (from header).
    pub normal_first_block_hash: [u8; 20],
}

#[derive(Debug, Clone, Copy, Serialize)]
pub struct BasicCompressionBlock {
    pub data_size: u32,
    pub zero_size: u32,
}

/// An imported library with its resolved imports.
#[derive(Debug, Clone, Serialize)]
pub struct ImportLibrary {
    pub name: String,
    pub id: u32,
    pub version_min: u32,
    pub version_cur: u32,
    /// Import entries. Before `resolve_imports`, these contain addresses but no ordinals.
    /// After `resolve_imports`, ordinals and record types are filled in from the PE image.
    pub imports: Vec<ImportEntry>,
}

/// A single import entry within an import library.
#[derive(Debug, Clone, Serialize)]
pub struct ImportEntry {
    pub ordinal: u16,
    pub record_type: u8, // 0 = variable, 1 = thunk
    pub address: u32,
}

/// Execution info parsed from the XEX header.
#[derive(Debug, Clone, Serialize)]
pub struct ExecutionInfo {
    pub media_id: u32,
    pub title_id: u32,
    pub disc_number: u8,
    pub disc_count: u8,
}

/// XEX2 magic: "XEX2"
pub const XEX2_MAGIC: u32 = 0x58455832;

/// Compression types
pub const COMPRESSION_NONE: u16 = 0;
pub const COMPRESSION_BASIC: u16 = 1;
pub const COMPRESSION_NORMAL: u16 = 2;

/// Encryption types
pub const ENCRYPTION_NONE: u16 = 0;
pub const ENCRYPTION_NORMAL: u16 = 1;

/// Optional header keys
pub mod header_keys {
    pub const ENTRY_POINT: u32 = 0x00010100;
    pub const IMAGE_BASE_ADDRESS: u32 = 0x00010201;
    pub const IMPORT_LIBRARIES: u32 = 0x000103FF;
    pub const TLS_INFO: u32 = 0x00020200;
    pub const EXECUTION_INFO: u32 = 0x00040006;
    pub const DEFAULT_STACK_SIZE: u32 = 0x00020104;
    pub const ORIGINAL_PE_NAME: u32 = 0x000183FF;
    pub const FILE_FORMAT_INFO: u32 = 0x000003FF;
    pub const SYSTEM_FLAGS: u32 = 0x00030000;
}
