use crate::ipc_types::Init as InitBlob;
use thiserror::Error;
use tokio::io::{self, AsyncBufReadExt, BufReader};

/// Errors that may occur while reading the initial handshake from stdin.
#[derive(Debug, Error)]
pub enum InitError {
    #[error("stdin closed unexpectedly during handshake")]
    StdinClosed,
    #[error("stdin read error: {0}")]
    Io(#[from] io::Error),
    #[error("failed to parse Init JSON: {0}")]
    Json(#[from] serde_json::Error),
}

/// Read the `Init` message sent by the orchestrator over **stdin**.
///
/// This should be called exactly once at startup, immediately after
/// `init_module()` so that logs are correctly configured.
///
/// The function reads a single line from `stdin`, trims trailing newlines, and
/// deserializes it into [`crate::ipc_types::Init`].
pub async fn read_init() -> Result<InitBlob, InitError> {
    let stdin = io::stdin();
    let mut reader = BufReader::new(stdin);
    let mut line = String::new();

    let bytes_read = reader.read_line(&mut line).await?;
    if bytes_read == 0 {
        return Err(InitError::StdinClosed);
    }

    let init: InitBlob = serde_json::from_str(line.trim_end_matches('\n'))?;
    Ok(init)
}
