//! Synor Storage Node Binary
//!
//! Runs a storage node that participates in the Synor Storage network.
//!
//! Usage:
//!   synor-storage-node --config /path/to/config.toml
//!   synor-storage-node --data-dir ./storage-data

use synor_storage::{NodeConfig, StorageNode, GatewayConfig, Gateway};
use std::path::PathBuf;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Initialize logging
    let log_level = std::env::var("RUST_LOG").unwrap_or_else(|_| "info".to_string());
    eprintln!("Starting Synor Storage Node (log level: {})", log_level);

    // Parse command line arguments
    let args: Vec<String> = std::env::args().collect();

    let config_path = args.iter()
        .position(|a| a == "--config")
        .map(|i| args.get(i + 1))
        .flatten()
        .cloned();

    let data_dir = args.iter()
        .position(|a| a == "--data-dir")
        .map(|i| args.get(i + 1))
        .flatten()
        .cloned()
        .unwrap_or_else(|| "./synor-storage-data".to_string());

    // Load configuration
    let node_config = if let Some(path) = config_path {
        eprintln!("Loading config from: {}", path);
        // TODO: Load from TOML file
        NodeConfig {
            data_dir: data_dir.clone(),
            ..NodeConfig::default()
        }
    } else {
        NodeConfig {
            data_dir: data_dir.clone(),
            ..NodeConfig::default()
        }
    };

    eprintln!("Data directory: {}", node_config.data_dir);
    eprintln!("Capacity: {} bytes", node_config.capacity);

    // Create and start the storage node
    eprintln!("Initializing storage node...");
    let node = StorageNode::new(node_config.clone()).await?;

    eprintln!("Starting storage node...");
    node.start().await?;

    let state = node.state().await;
    eprintln!("Node state: {:?}", state);

    // Start the gateway if enabled
    let gateway_enabled = std::env::var("GATEWAY_ENABLED")
        .map(|v| v == "true" || v == "1")
        .unwrap_or(true);

    if gateway_enabled {
        let gateway_config = GatewayConfig {
            listen_addr: std::env::var("GATEWAY_ADDR").unwrap_or_else(|_| "0.0.0.0:8080".to_string()),
            ..GatewayConfig::default()
        };

        eprintln!("Starting gateway on {}...", gateway_config.listen_addr);
        let gateway = Gateway::new(gateway_config);
        gateway.start().await?;
    }

    eprintln!("Storage node is running!");
    eprintln!("Press Ctrl+C to stop");

    // Wait for shutdown signal
    tokio::signal::ctrl_c().await?;

    eprintln!("\nShutting down...");
    node.stop().await?;
    eprintln!("Storage node stopped");

    Ok(())
}
