//! Server Node entry point.
//!
//! This module initializes the headless relay server, binds the network listeners,
//! and spawns isolated tasks for each connected TCP client.

#![forbid(unsafe_code)]
#![deny(clippy::all, clippy::pedantic)]
#![deny(clippy::unwrap_used, clippy::expect_used)]

mod state;
mod tcp_router;

use core_protocol::constants;
use state::AppState;
use std::sync::Arc;
use tokio::net::TcpListener;
use tracing::{error, info};

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    tracing_subscriber::fmt::init();
    info!("Starting server node...");

    let state = Arc::new(AppState::new());

    let addr = format!("0.0.0.0:{}", constants::TCP_PORT);
    let listener = TcpListener::bind(&addr).await?;
    info!("TCP Listener bound to {}", addr);

    loop {
        match listener.accept().await {
            Ok((stream, _)) => {
                let state_clone = state.clone();
                tokio::spawn(async move {
                    tcp_router::handle_connection(stream, state_clone).await;
                });
            }
            Err(e) => {
                error!("Failed to accept connection: {:?}", e);
            }
        }
    }
}
