use clap::Parser;
use flaredb_proto::pdpb::pd_server::PdServer;
use flaredb_proto::pdpb::tso_server::TsoServer;
use std::sync::Arc;
use tonic::transport::Server;

mod cluster;
mod pd_service;
mod service;
mod tso;

#[derive(Parser, Debug)]
#[command(author, version, about, long_about = None)]
struct Args {
    #[arg(long, default_value = "127.0.0.1:2479")]
    addr: String,
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let args = Args::parse();
    let addr = args.addr.parse()?;

    println!("rdb-pd listening on {}", addr);

    let tso_oracle = Arc::new(tso::TsoOracle::new());
    // Use TsoServiceImpl for TsoServer (legacy)
    let tso_service = service::TsoServiceImpl::new(tso_oracle.clone());

    // Use PdServiceImpl for PdServer (new)
    let pd_service = pd_service::PdServiceImpl::new(tso_oracle);

    Server::builder()
        .add_service(TsoServer::new(tso_service))
        .add_service(PdServer::new(pd_service))
        .serve(addr)
        .await?;

    Ok(())
}
