//! [TSM.ID].[11031972] — Platform X Ecosystem
//! Platform detection and capability matrix

use crate::{Platform, Result, BridgeError};
use serde::{Serialize, Deserialize};

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PlatformCapabilities {
    pub has_webview: bool,
    pub has_native_bridge: bool,
    pub supports_wasm: bool,
    pub max_message_size: usize,
    pub supports_binary: bool,
    pub supports_streaming: bool,
}

pub struct PlatformDetector;

impl PlatformDetector {
    pub fn detect() -> Platform {
        #[cfg(target_os = "android")]
        return Platform::Android;
        #[cfg(target_os = "ios")]
        return Platform::Ios;
        #[cfg(target_arch = "wasm32")]
        return Platform::WebAssembly;
        #[cfg(not(any(target_os = "android", target_os = "ios", target_arch = "wasm32")))]
        Platform::Desktop
    }

    pub fn capabilities(platform: &Platform) -> PlatformCapabilities {
        match platform {
            Platform::Android => PlatformCapabilities {
                has_webview: true, has_native_bridge: true, supports_wasm: true,
                max_message_size: 1_048_576, supports_binary: true, supports_streaming: true,
            },
            Platform::Ios => PlatformCapabilities {
                has_webview: true, has_native_bridge: true, supports_wasm: true,
                max_message_size: 1_048_576, supports_binary: true, supports_streaming: true,
            },
            Platform::HarmonyOs => PlatformCapabilities {
                has_webview: true, has_native_bridge: true, supports_wasm: true,
                max_message_size: 524_288, supports_binary: true, supports_streaming: false,
            },
            Platform::Desktop => PlatformCapabilities {
                has_webview: true, has_native_bridge: true, supports_wasm: true,
                max_message_size: 16_777_216, supports_binary: true, supports_streaming: true,
            },
            Platform::WebAssembly => PlatformCapabilities {
                has_webview: false, has_native_bridge: false, supports_wasm: true,
                max_message_size: 4_194_304, supports_binary: true, supports_streaming: true,
            },
        }
    }

    pub fn validate_message_size(platform: &Platform, size: usize) -> Result<()> {
        let caps = Self::capabilities(platform);
        if size > caps.max_message_size {
            return Err(BridgeError::SerializationFailed(
                format!("Message size {size} exceeds platform limit {}", caps.max_message_size)
            ));
        }
        Ok(())
    }
}
