use std::borrow::Cow;
use std::path::Path;

use secrecy::{ExposeSecret, SecretBox};
use testcontainers::core::{ContainerPort, ContainerRequest, Mount, WaitFor};
use testcontainers::runners::AsyncRunner;
use testcontainers::{ContainerAsync, Image, ImageExt};
use tracing::Level;
use url::Url;

use crate::containers::{ContainerConfig, ContainerLogConsumer, ImageConfig};
use crate::helpers::{self, TempPathWithString};

/// Database URL.
const DATABASE_URL_KEY: &str = "FLORA_DATABASE_URL";

/// The environment variable name for
/// the message the Omry server should print to stdout when it's ready to receive requests.
const READY_MESSAGE_KEY: &str = "FLORA_READY_MESSAGE";

/// The tracing level for the Omry server.
const TRACING_LEVEL_KEY: &str = "FLORA_TRACING_LEVEL";

/// The Typesense API key used by the Omry server.
const TYPESENSE_API_KEY_KEY: &str = "FLORA_TYPESENSE_API_KEY";

/// Typesense URL the Omry server should connect to.
const TYPESENSE_URL_KEY: &str = "FLORA_TYPESENSE_URL";

/// The path to the data directory used by Omry inside the container.
const DATA_PATH_CONTAINER: &str = "/usr/local/etc/flora";

/// This image name assumes the image is stored in the local registry.
const IMAGE_NAME: &str = "localhost:8777/omry-server";

/// Omry server image tag.
const IMAGE_TAG: &str = "latest";

/// The port the Omry server should bind to inside the container.
const CONTAINER_PORT: u16 = 37373;

/// The message the Omry server should print to stdout when it's ready to receive requests.
const READY_MESSAGE: &str = "flora is ready!";

/// Enum to encode plain or secret environment variables
/// for the flora server image.
#[derive(Debug)]
pub enum EnvVar {
    /// Plain (not secret) environment variable.
    Plain {
        /// Key (variable name).
        key: String,

        /// Value.
        value: String,
    },

    /// Secret environment variable, whose value should not be unintentionally exposed.
    Secret {
        /// Key (variable name).
        key: String,

        /// Value (will be stored in [`SecretBox`]).
        value: SecretBox<str>,
    },
}

impl EnvVar {
    /// Returns this environment variable as a string (key, value) pair.
    fn as_key_value_pair(&self) -> (&str, &str) {
        match self {
            Self::Plain { key, value } => (key, value),
            Self::Secret { key, value } => (key, value.expose_secret()),
        }
    }
}

/// flora image config.
#[allow(clippy::missing_docs_in_private_items)]
#[derive(Debug)]
pub struct FloraConfig {
    database_url: EnvVar,
    ready_message: EnvVar,
    tracing_level: Option<EnvVar>,
    typesense_api_key: EnvVar,
    typesense_url: EnvVar,
}

impl FloraConfig {
    /// Initializes a new flora image config with the given parameters.
    #[must_use]
    pub fn new(typesense_url: &Url, typesense_api_key: SecretBox<str>) -> Self {
        let typesense_api_key = EnvVar::Secret {
            key: TYPESENSE_API_KEY_KEY.to_string(),
            value: typesense_api_key,
        };
        let typesense_url = EnvVar::Plain {
            key: TYPESENSE_URL_KEY.to_string(),
            value: typesense_url.to_string(),
        };

        // Hardcode the ready message until we have a reason to let the caller configure it.
        let ready_message = EnvVar::Plain {
            key: READY_MESSAGE_KEY.to_string(),
            value: READY_MESSAGE.to_string(),
        };

        let db_path = Path::new(DATA_PATH_CONTAINER)
            .join("flora.db")
            .display()
            .to_string();

        // ditto with database URL.
        let database_url = EnvVar::Plain {
            key: DATABASE_URL_KEY.into(),
            value: db_path,
        };

        Self {
            typesense_api_key,
            typesense_url,
            ready_message,
            database_url,
            tracing_level: None,
        }
    }

    /// Sets the tracing level for the flora RPC server.
    #[must_use]
    pub fn with_tracing_level(mut self, tracing_level: Level) -> Self {
        let tracing_level = EnvVar::Plain {
            key: TRACING_LEVEL_KEY.into(),
            value: tracing_level.to_string(),
        };
        self.tracing_level = Some(tracing_level);
        self
    }

    /// Returns the values in this config as a vec of environment variables.
    fn into_vec(self) -> Vec<EnvVar> {
        let mut vars = vec![
            self.database_url,
            self.ready_message,
            self.typesense_url,
            self.typesense_api_key,
        ];

        if let Some(tracing_level) = self.tracing_level {
            vars.push(tracing_level);
        }

        vars
    }
}

/// Omry server image for integration tests.
#[allow(clippy::missing_docs_in_private_items)]
#[derive(Debug)]
pub struct FloraImage {
    name: String,
    tag: String,
    env: Vec<EnvVar>,
    mounts: Vec<Mount>,
    container_ports: Vec<ContainerPort>,
    ready_message: String,
    host_port: Option<u16>,
    // We need to store this on the struct so the temp directory
    // sticks around until the struct is dropped.
    #[allow(dead_code)]
    data_temp_path: TempPathWithString,
}

impl FloraImage {
    /// Creates a new flora image instance with the given flora server config and
    /// Docker image config.
    ///
    /// ## Errors
    /// Returns [`anyhow::Error`] if we can't create a temporary path for Omry's data.
    pub fn new(flora_config: FloraConfig, image_config: ImageConfig) -> anyhow::Result<Self> {
        let data_temp_path = TempPathWithString::new()?;
        let mount = Mount::bind_mount(data_temp_path.as_str(), DATA_PATH_CONTAINER);
        let container_ports = if image_config.should_expose_ports {
            vec![ContainerPort::Tcp(CONTAINER_PORT)]
        } else {
            vec![]
        };

        let (_, ready_message) = flora_config.ready_message.as_key_value_pair();
        let ready_message = ready_message.into();

        Ok(Self {
            name: IMAGE_NAME.to_string(),
            tag: IMAGE_TAG.to_string(),
            env: flora_config.into_vec(),
            data_temp_path,
            mounts: vec![mount],
            container_ports,
            ready_message,
            host_port: None,
        })
    }

    /// Configures this container to request any free port from the host OS.
    fn with_auto_host_port(mut self) -> ContainerRequest<Self> {
        let (_, host_port) = helpers::free_port_ipv6();
        self.host_port = Some(host_port);
        self.with_mapped_port(host_port, CONTAINER_PORT.into())
    }

    /// Returns the host-side port this container is bound to (if any).
    #[must_use]
    pub fn host_port(&self) -> Option<u16> {
        self.host_port
    }
}

impl Image for FloraImage {
    fn name(&self) -> &str {
        &self.name
    }

    fn tag(&self) -> &str {
        &self.tag
    }

    fn ready_conditions(&self) -> Vec<WaitFor> {
        vec![WaitFor::message_on_stdout(&self.ready_message)]
    }

    fn env_vars(
        &self,
    ) -> impl IntoIterator<Item = (impl Into<Cow<'_, str>>, impl Into<Cow<'_, str>>)> {
        self.env.iter().map(EnvVar::as_key_value_pair)
    }

    fn mounts(&self) -> impl IntoIterator<Item = &Mount> {
        &self.mounts
    }

    fn expose_ports(&self) -> &[ContainerPort] {
        &self.container_ports
    }
}

/// Type alias to reduce the type signature.
pub type FloraContainer = ContainerAsync<FloraImage>;

/// Starts an Omry RPC server container for integration tests.
///
/// ## Errors
/// Returns [`anyhow::Error`] if we can't start the Omry server.
pub async fn start_flora_container<L>(
    flora_config: FloraConfig,
    container_config: ContainerConfig<L>,
) -> anyhow::Result<FloraContainer>
where
    L: ContainerLogConsumer,
{
    let flora_container =
        FloraImage::new(flora_config, container_config.image_config)?.with_auto_host_port();
    let flora_container = container_config.configure_container(flora_container);
    Ok(flora_container.start().await?)
}
