//! Public rewrite shell corresponding to the main `LibreMetaverse` assembly.

extern crate self as libremetaverse;

#[rustfmt::skip] // Deterministic machine output is formatted by the pinned generator.
mod attention_catalog;
mod agent_manager;
mod agent_messages;
mod agent_movement;
mod animation;
#[path = "animesh.rs"]
mod animesh_runtime;
mod animesh_skinning;
mod appearance_baker;
mod appearance_manager;
mod asset_archive;
mod asset_cache;
mod asset_manager;
mod asset_material;
mod asset_models;
mod avatar_manager;
mod avatar_rig;
mod baking_texture_provider;
mod bit_pack;
mod caps;
mod caps_http;
mod client_core;
mod current_outfit;
mod download_manager;
mod environment_manager;
mod estate_tools;
mod event_queue;
mod friends_manager;
mod gesture;
mod gltf;
mod group_manager;
mod initial_outfit;
mod inventory;
mod inventory_ais;
mod inventory_manager;
#[rustfmt::skip] // Deterministic machine output is formatted by the pinned generator.
mod foliage_catalog;
mod generated;
#[rustfmt::skip] // Deterministic machine output is formatted by the pinned generator.
mod genepool_catalog;
mod j2k;
mod login;
#[path = "marketplace.rs"]
mod marketplace_runtime;
mod message_codec;
mod message_decoder;
mod model_workflow;
mod network_manager;
mod object_manager;
mod object_material;
mod object_model;
#[rustfmt::skip]
pub mod packet_catalog;
mod directory_manager;
mod grid_manager;
pub use grid_manager::MapItemData;
mod interest_list;
mod packet_wire;
mod parcel_manager;
mod sim_stats;
mod skeleton;
mod slurl;
mod sound_manager;
#[rustfmt::skip] // Deterministic machine output is formatted by the pinned generator.
mod skeleton_catalog;
mod targa;
mod terrain_codec;
mod terrain_manager;
mod transfers;
mod udp_transport;
mod user_report;
#[rustfmt::skip] // Deterministic machine output is formatted by the pinned generator.
mod visual_catalog;

#[cfg(test)]
mod appearance_baker_semantics;
#[cfg(test)]
mod asset_archive_semantics;
#[cfg(test)]
mod asset_pipeline_semantics;
#[cfg(test)]
mod avatar_animesh_semantics;
#[cfg(test)]
mod batch_link_internal_semantics;
#[cfg(test)]
mod inventory_ais_internal_semantics;
#[cfg(test)]
mod world_internal_semantics;

type Terrain = Vec<Vec<f32>>;
type TerrainLoaded = Box<dyn Fn(Terrain, i64, i64) + Send + Sync>;

impl assets::OarFile {
    #[allow(dead_code, clippy::needless_pass_by_value)]
    fn load_terrain(
        file_path: &str,
        data: Vec<u8>,
        callback: TerrainLoaded,
        bytes_read: i64,
        total_bytes: i64,
    ) -> Result<bool, Error> {
        crate::asset_archive::load_terrain(file_path, &data, callback, bytes_read, total_bytes)
    }
}

#[allow(dead_code)]
impl animesh::AnimationTrack {
    fn new(animation_id: libremetaverse_types::UUID) -> Result<Self, Error> {
        Self::native_new(animation_id)
    }

    fn decode_rotation(
        value: libremetaverse_types::Vector3,
    ) -> Result<libremetaverse_types::Quaternion, Error> {
        Self::native_decode_rotation(value)
    }
}

#[allow(
    clippy::needless_pass_by_value,
    clippy::unnecessary_wraps,
    clippy::unused_self,
    dead_code
)]
impl animesh::AnimeshPlayer {
    fn new(object_id: libremetaverse_types::UUID) -> Result<Self, Error> {
        Self::native_new(object_id)
    }

    fn get_or_add_track(
        &mut self,
        animation_id: libremetaverse_types::UUID,
    ) -> Result<std::sync::Arc<animesh::AnimationTrack>, Error> {
        self.native_get_or_add_track(animation_id)
    }

    fn retain_only(
        &mut self,
        animation_ids: std::collections::HashSet<libremetaverse_types::UUID>,
    ) -> Result<(), Error> {
        self.native_retain_only(&animation_ids);
        Ok(())
    }
}

#[allow(dead_code)] // Internal C# surface consumed by InventoryManager workflows.
impl InventoryAISClient {
    async fn create_inventory_links(
        &self,
        parent_uuid: libremetaverse_types::UUID,
        new_inventory: libremetaverse_structured_data::OSD,
        cancellation_token: Option<libremetaverse_types::compat::CancellationToken>,
    ) -> Result<Vec<InventoryItem>, Error> {
        self.native_create_inventory_links(parent_uuid, new_inventory, cancellation_token)
            .await
    }
}

#[allow(dead_code, clippy::needless_pass_by_value, clippy::unnecessary_wraps)]
impl NetworkManager {
    fn raise_sim_console_response(
        &self,
        message: messages::linden::SimConsoleResponseMessage,
        simulator: Simulator,
    ) -> Result<(), Error> {
        self.dispatch_caps_event("SimConsoleResponse", &message, simulator);
        Ok(())
    }
}

#[allow(dead_code)]
impl imaging::Baker {
    fn resize_to_bake_dimensions(
        source: libremetaverse_imaging::ManagedImage,
        width: i32,
        height: i32,
    ) -> Result<Option<libremetaverse_imaging::ManagedImage>, Error> {
        crate::appearance_baker::Baker::native_resize_to_bake_dimensions(source, width, height)
    }
}

pub use caps_http::CapsHttpLimits;
pub use client_core::{
    ClientCoreError, ClientLifecycleState, ClientService, GridClientBuilder, ShutdownPhase,
};
pub use generated::*;
pub use libremetaverse_imaging as imaging_abstractions;
pub use libremetaverse_structured_data as structured_data;
pub use libremetaverse_types as types;
pub use libremetaverse_types::Error;
pub use network_manager::SimulatorCollection;
pub use udp_transport::{
    AgentThrottleSender, UdpPacketHandler, UdpThrottleCategory, UdpTransportConfig,
    UdpTransportError, UdpTransportStats,
};
pub use user_report::{UserReport, UserReportService, UserReportType};

pub(crate) fn is_offline_fixture_uri(uri: &libremetaverse_types::compat::Uri) -> bool {
    reqwest::Url::parse(&uri.0)
        .ok()
        .and_then(|url| url.host_str().map(str::to_owned))
        .is_some_and(|host| host == "invalid" || host.ends_with(".invalid"))
}

/// Rust object-safe view of the C# `InventoryBase` inheritance hierarchy.
pub trait InventoryObjectClass: std::any::Any {
    /// Returns the concrete value for exact C# runtime-type checks.
    fn as_any(&self) -> &dyn std::any::Any;

    /// Returns the shared `InventoryBase` portion of the concrete object.
    fn inventory_base(&self) -> &InventoryBase;

    /// Returns the shared `InventoryItem` portion for item-derived objects.
    fn inventory_item(&self) -> Option<&InventoryItem> {
        None
    }
}

/// Rust object-safe view of concrete classes derived from C# `InventoryItem`.
pub trait InventoryItemClass: InventoryObjectClass {}

macro_rules! inventory_object_class {
    ($type:ty, $base:ident $(.$nested:ident)*) => {
        impl InventoryObjectClass for $type {
            fn as_any(&self) -> &dyn std::any::Any {
                self
            }

            fn inventory_base(&self) -> &InventoryBase {
                &self.$base$(.$nested)*
            }
        }
    };
}

macro_rules! inventory_item_class {
    ($type:ty, $item:ident $(.$nested:ident)*) => {
        impl InventoryObjectClass for $type {
            fn as_any(&self) -> &dyn std::any::Any {
                self
            }

            fn inventory_base(&self) -> &InventoryBase {
                &self.$item$(.$nested)*.base
            }

            fn inventory_item(&self) -> Option<&InventoryItem> {
                Some(&self.$item$(.$nested)*)
            }
        }
    };
}

impl InventoryObjectClass for InventoryBase {
    fn as_any(&self) -> &dyn std::any::Any {
        self
    }

    fn inventory_base(&self) -> &InventoryBase {
        self
    }
}

inventory_object_class!(InventoryFolder, base);
impl InventoryObjectClass for InventoryItem {
    fn as_any(&self) -> &dyn std::any::Any {
        self
    }

    fn inventory_base(&self) -> &InventoryBase {
        &self.base
    }

    fn inventory_item(&self) -> Option<&InventoryItem> {
        Some(self)
    }
}
inventory_item_class!(InventoryAnimation, base);
inventory_item_class!(InventoryAttachment, base);
inventory_item_class!(InventoryCallingCard, base);
inventory_item_class!(InventoryCategory, base);
inventory_item_class!(InventoryGesture, base);
inventory_item_class!(InventoryLSL, base);
inventory_item_class!(InventoryLandmark, base);
inventory_item_class!(InventoryMaterial, base);
inventory_item_class!(InventoryNotecard, base);
inventory_item_class!(InventoryObject, base);
inventory_item_class!(InventorySettings, base);
inventory_item_class!(InventorySnapshot, base);
inventory_item_class!(InventorySound, base);
inventory_item_class!(InventoryTexture, base);
inventory_item_class!(InventoryWearable, base);

impl InventoryItemClass for InventoryItem {}
impl InventoryItemClass for InventoryAnimation {}
impl InventoryItemClass for InventoryAttachment {}
impl InventoryItemClass for InventoryCallingCard {}
impl InventoryItemClass for InventoryCategory {}
impl InventoryItemClass for InventoryGesture {}
impl InventoryItemClass for InventoryLSL {}
impl InventoryItemClass for InventoryLandmark {}
impl InventoryItemClass for InventoryMaterial {}
impl InventoryItemClass for InventoryNotecard {}
impl InventoryItemClass for InventoryObject {}
impl InventoryItemClass for InventorySettings {}
impl InventoryItemClass for InventorySnapshot {}
impl InventoryItemClass for InventorySound {}
impl InventoryItemClass for InventoryTexture {}
impl InventoryItemClass for InventoryWearable {}

/// Project-owned boundary types for external `MessagePack` signatures.
pub mod message_pack {
    pub trait IMessagePackFormatter<T = ()> {}
    pub struct MessagePackReader;
    pub struct MessagePackSerializerOptions;
    pub struct MessagePackWriter;
}

/// Project-owned boundary types for external logging signatures.
pub mod logging {
    pub trait ILoggerFactory {}

    #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
    pub struct LogLevel(pub i32);
}

/// Project-owned boundary types for external networking signatures.
pub mod net {
    pub struct RateLimiter;
    pub struct Socket;
    pub struct TcpStream;
    pub struct UdpSocket;
}

/// Project-owned boundary types for external service-collection signatures.
pub mod services {
    pub trait IServiceCollection {}
}

/// Common behavior for program shims while the network stack is unimplemented.
pub mod shim {
    use std::process::ExitCode;

    /// Reports that an upstream sample has a target but no implementation yet.
    #[must_use]
    pub fn pending_program(name: &str) -> ExitCode {
        eprintln!("{name}: LibreMetaverse Rust port is not implemented yet");
        ExitCode::FAILURE
    }
}
