//! 独立 Worker 客户端；帧、异步管道和期限直接使用 Tokio/tokio-util。
use bytes::Bytes;
use futures_util::{SinkExt, StreamExt};
use serde::Deserialize;
use serde_json::{Value, json};
use std::{error::Error, process::Stdio, time::Duration};
use tokio::{process::{Child, ChildStdin, ChildStdout, Command}, time::timeout};
use tokio_util::codec::{FramedRead, FramedWrite, LengthDelimitedCodec};
type Result<T> = std::result::Result<T, Box<dyn Error + Send + Sync>>;
const LIMIT: usize = 16 * 1024 * 1024;
const DEADLINE: Duration = Duration::from_secs(2);

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Input { values: Vec<String> }
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Reply { kind: String, id: u64, payload: Value }
struct Worker {
    child: Child,
    input: FramedWrite<ChildStdin, LengthDelimitedCodec>,
    output: FramedRead<ChildStdout, LengthDelimitedCodec>,
    next: u64,
}
impl Worker {
    async fn start(path: &str) -> Result<Self> {
        let mut child = Command::new(path).stdin(Stdio::piped()).stdout(Stdio::piped())
            .stderr(Stdio::inherit()).kill_on_drop(true).spawn()?;
        let mut worker = Self {
            input: LengthDelimitedCodec::builder().max_frame_length(LIMIT).new_write(child.stdin.take().unwrap()),
            output: LengthDelimitedCodec::builder().max_frame_length(LIMIT).new_read(child.stdout.take().unwrap()),
            child, next: 1,
        };
        let hello = json!({"kind":"hello","version":"dever-component-1","port":"benchmark.echo","schema":"independent-reference","adapter":"default","capabilities":[],"operations":["echo","unit"],"setting":null});
        worker.send(&hello).await?;
        let mut ready = hello;
        ready.as_object_mut().unwrap().remove("setting");
        ready["kind"] = "ready".into();
        if worker.read().await? != ready { return Err("Worker handshake mismatch".into()); }
        let health = json!({"kind":"health","id":0});
        worker.send(&health).await?;
        if worker.read().await? != health { return Err("Worker health mismatch".into()); }
        Ok(worker)
    }
    async fn send(&mut self, value: &Value) -> Result<()> {
        timeout(DEADLINE, self.input.send(Bytes::from(serde_json::to_vec(value)?))).await??;
        Ok(())
    }
    async fn read(&mut self) -> Result<Value> {
        let bytes = timeout(DEADLINE, self.output.next()).await?
            .ok_or("Worker closed its output")??;
        Ok(serde_json::from_slice(&bytes)?)
    }
    async fn call(&mut self, operation: &str, payload: Value) -> Result<Value> {
        let id = self.next;
        self.next += 1;
        self.send(&json!({"kind":"call","id":id,"operation":operation,"payload":payload})).await?;
        let reply: Reply = serde_json::from_value(self.read().await?)?;
        if reply.kind != "result" || reply.id != id { return Err("Worker response identity mismatch".into()); }
        Ok(reply.payload)
    }
    async fn stop(&mut self) -> Result<()> {
        let shutdown = json!({"kind":"shutdown","id":0});
        self.send(&shutdown).await?;
        if self.read().await? != shutdown { return Err("Worker shutdown mismatch".into()); }
        if !timeout(DEADLINE, self.child.wait()).await??.success() { return Err("Worker exited unsuccessfully".into()); }
        Ok(())
    }
}
async fn execute(path: &str, input: Input) -> Result<Vec<String>> {
    let mut worker = Worker::start(path).await?;
    let result = async {
        if worker.call("unit", json!({})).await? != json!({}) { return Err("invalid unit output".into()); }
        let mut results = Vec::with_capacity(input.values.len());
        #[derive(Deserialize)]
        #[serde(deny_unknown_fields)]
        struct Echo { out: String }
        for value in input.values {
            let output: Echo = serde_json::from_value(worker.call("echo", json!({"value":value})).await?)?;
            results.push(output.out);
        }
        Ok(results)
    }.await;
    match result {
        Ok(values) => { worker.stop().await?; Ok(values) }
        Err(error) => {
            worker.child.kill().await?;
            worker.child.wait().await?;
            Err(error)
        }
    }
}
fn main() -> Result<()> {
    let mut args = std::env::args().skip(1);
    let worker = args.next().ok_or("Worker path is required")?;
    let input: Input = serde_json::from_str(&args.next().ok_or("input is required")?)?;
    let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build()?;
    let values = runtime.block_on(execute(&worker, input))?;
    println!("{}", serde_json::to_string(&values)?);
    Ok(())
}
