//! Rhai wrappers for network module functions
//!
//! This module provides Rhai wrappers for network connectivity functions.
//! All functions are prefixed with `net_` to avoid naming conflicts.
//!
//! ## TCP Functions
//! - `net_tcp_check(host, port)` - Check if TCP port is open
//! - `net_tcp_ping(host)` - Ping a host using ICMP
//!
//! ## HTTP Functions
//! - `net_http_check(url)` - Check if HTTP URL is reachable
//! - `net_http_status(url)` - Get HTTP status code
//!
//! ## SSH Functions
//! - `ssh_builder()` - Create SSH connection builder
//! - Builder methods: `.host()`, `.port()`, `.user()`, `.ssh_private_key_path()`, `.timeout_secs()`, `.build()`
//! - Connection methods: `.execute(cmd)`, `.ping()`, `.file_transfer()`
//! - File transfer methods: `.archive()`, `.verbose()`, `.compress()`, `.delete()`, `.exclude()`, `.exclude_patterns()`, `.push()`, `.pull()`

use super::ssh::rhai::register_ssh_module;
use rhai::{Engine, EvalAltResult};

/// Register network module functions with the Rhai engine
pub fn register_net_module(engine: &mut Engine) -> Result<(), Box<EvalAltResult>> {
    // TCP functions (prefixed with net_)
    engine.register_fn("net_tcp_check", net_tcp_check);
    engine.register_fn("net_tcp_ping", net_tcp_ping);

    // HTTP functions (prefixed with net_)
    engine.register_fn("net_http_check", net_http_check);
    engine.register_fn("net_http_status", net_http_status);

    // SSH module
    register_ssh_module(engine)?;

    Ok(())
}

/// Check if a TCP port is open
pub fn net_tcp_check(host: &str, port: i64) -> bool {
    // Use std::net::TcpStream for synchronous connection test
    use std::net::{SocketAddr, TcpStream};
    use std::time::Duration;

    // Parse the address
    let addr_str = format!("{}:{}", host, port);
    if let Ok(socket_addr) = addr_str.parse::<SocketAddr>() {
        // Try to connect with a timeout
        TcpStream::connect_timeout(&socket_addr, Duration::from_secs(5)).is_ok()
    } else {
        // Try to resolve hostname first
        match std::net::ToSocketAddrs::to_socket_addrs(&addr_str) {
            Ok(mut addrs) => {
                if let Some(addr) = addrs.next() {
                    TcpStream::connect_timeout(&addr, Duration::from_secs(5)).is_ok()
                } else {
                    false
                }
            }
            Err(_) => false,
        }
    }
}

/// Ping a host using ICMP (cross-platform)
pub fn net_tcp_ping(host: &str) -> bool {
    // Use system ping command for synchronous operation
    use std::process::Command;

    // Cross-platform ping implementation
    let mut cmd = Command::new("ping");

    #[cfg(target_os = "windows")]
    {
        cmd.arg("-n").arg("1").arg("-w").arg("5000"); // Windows: -n count, -w timeout in ms
    }

    #[cfg(not(target_os = "windows"))]
    {
        cmd.arg("-c").arg("1").arg("-W").arg("5"); // Unix: -c count, -W timeout in seconds
    }

    cmd.arg(host);

    match cmd.output() {
        Ok(output) => output.status.success(),
        Err(_) => false,
    }
}

/// Check if an HTTP URL is reachable
pub fn net_http_check(url: &str) -> bool {
    use std::time::Duration;

    let agent = ureq::Agent::new_with_config(
        ureq::Agent::config_builder()
            .timeout_global(Some(Duration::from_secs(10)))
            .build(),
    );

    match agent.head(url).call() {
        Ok(response) => response.status().is_success(),
        Err(_) => false,
    }
}

/// Get HTTP status code from a URL
pub fn net_http_status(url: &str) -> i64 {
    use std::time::Duration;

    let agent = ureq::Agent::new_with_config(
        ureq::Agent::config_builder()
            .timeout_global(Some(Duration::from_secs(10)))
            .build(),
    );

    match agent.head(url).call() {
        Ok(response) => response.status().as_u16() as i64,
        Err(_) => -1,
    }
}
