// 独立客户端使用标准库的管道、长度帧和进程等待，不导入 Dever。
package main

import (
    "bytes"
    "encoding/binary"
    "encoding/json"
    "errors"
    "fmt"
    "io"
    "os"
    "os/exec"
)

const limit = 16 * 1024 * 1024

type worker struct { command *exec.Cmd; input io.WriteCloser; output io.ReadCloser; next uint64; waited bool }
func (w *worker) send(value any) error {
    body, err := json.Marshal(value)
    if err != nil { return err }
    if len(body) > limit { return errors.New("Worker frame exceeds byte limit") }
    var prefix [4]byte
    binary.BigEndian.PutUint32(prefix[:],uint32(len(body)))
    _, err = io.Copy(w.input, io.MultiReader(bytes.NewReader(prefix[:]), bytes.NewReader(body)))
    return err
}
func (w *worker) read(target any) error {
    var prefix [4]byte
    if _,err:=io.ReadFull(w.output,prefix[:]); err!=nil { return err }
    length:=binary.BigEndian.Uint32(prefix[:])
    if length==0 || length>limit { return errors.New("invalid Worker frame length") }
    body:=make([]byte,length)
    if _,err:=io.ReadFull(w.output,body); err!=nil { return err }
    decoder:=json.NewDecoder(bytes.NewReader(body))
    decoder.DisallowUnknownFields()
    return decoder.Decode(target)
}
func (w *worker) identity(kind string) error {
    message:=map[string]any{"kind":kind,"id":0}
    if err:=w.send(message); err!=nil { return err }
    var reply struct {Kind string `json:"kind"`; ID uint64 `json:"id"`}
    if err:=w.read(&reply); err!=nil { return err }
    if reply.Kind!=kind || reply.ID!=0 { return errors.New("Worker identity mismatch") }
    return nil
}
func (w *worker) call(operation string,payload any,target any) error {
    id:=w.next
    w.next++
    if err:=w.send(map[string]any{"kind":"call","id":id,"operation":operation,"payload":payload}); err!=nil { return err }
    var reply struct {Kind string `json:"kind"`; ID uint64 `json:"id"`; Payload json.RawMessage `json:"payload"`}
    if err:=w.read(&reply); err!=nil { return err }
    if reply.Kind!="result" || reply.ID!=id { return errors.New("Worker response identity mismatch") }
    decoder:=json.NewDecoder(bytes.NewReader(reply.Payload))
    decoder.DisallowUnknownFields()
    return decoder.Decode(target)
}
func run(path string, values []string) (results []string, failure error) {
    command:=exec.Command(path)
    input,err:=command.StdinPipe()
    if err!=nil { return nil,err }
    output,err:=command.StdoutPipe()
    if err!=nil { return nil,err }
    command.Stderr=os.Stderr
    if err=command.Start(); err!=nil { return nil,err }
    w:=worker{command:command,input:input,output:output,next:1}
    defer func(){
        if !w.waited {
            failure=errors.Join(failure,command.Process.Kill(),command.Wait())
        }
    }()
    hello:=map[string]any{"kind":"hello","version":"dever-component-1","port":"benchmark.echo","schema":"independent-reference","adapter":"default","capabilities":[]string{},"operations":[]string{"echo","unit"},"setting":nil}
    if err=w.send(hello); err!=nil { return nil,err }
    delete(hello,"setting")
    hello["kind"]="ready"
    expected,_:=json.Marshal(hello)
    var ready map[string]json.RawMessage
    if err=w.read(&ready); err!=nil { return nil,err }
    actual,_:=json.Marshal(ready)
    if !bytes.Equal(actual,expected) { return nil,errors.New("Worker handshake mismatch") }
    if err=w.identity("health"); err!=nil { return nil,err }
    var unit struct{}
    if err=w.call("unit",struct{}{},&unit); err!=nil { return nil,err }
    results=make([]string,0,len(values))
    for _,value:=range values {
        var reply struct{Out string `json:"out"`}
        if err=w.call("echo",map[string]string{"value":value},&reply); err!=nil { return nil,err }
        results=append(results,reply.Out)
    }
    if err=w.identity("shutdown"); err!=nil { return nil,err }
    failure=command.Wait()
    w.waited=true
    return results,failure
}
func main(){
    if len(os.Args)!=3 { fmt.Fprintln(os.Stderr,"expected Worker and input");os.Exit(1) }
    // 输入只有一个必填字段，Token/Decode 直接拒绝未知、重复、缺失与尾随内容。
    decoder:=json.NewDecoder(bytes.NewBufferString(os.Args[2]))
    begin,err:=decoder.Token()
    if err!=nil || begin!=json.Delim('{') { fmt.Fprintln(os.Stderr,"invalid input object");os.Exit(1) }
    field,err:=decoder.Token()
    if err!=nil || field!="values" { fmt.Fprintln(os.Stderr,"expected values");os.Exit(1) }
    start,err:=decoder.Token()
    if err!=nil || start!=json.Delim('[') { fmt.Fprintln(os.Stderr,"expected text list");os.Exit(1) }
    values:=[]string{}
    for decoder.More() {
        token,err:=decoder.Token()
        value,ok:=token.(string)
        if err!=nil || !ok { fmt.Fprintln(os.Stderr,"expected text element",err);os.Exit(1) }
        values=append(values,value)
    }
    if _,err=decoder.Token(); err!=nil { fmt.Fprintln(os.Stderr,err);os.Exit(1) }
    end,err:=decoder.Token()
    if err!=nil || end!=json.Delim('}') { fmt.Fprintln(os.Stderr,"unexpected input field");os.Exit(1) }
    if _,err=decoder.Token(); !errors.Is(err,io.EOF) { fmt.Fprintln(os.Stderr,"unexpected trailing input");os.Exit(1) }
    result,err:=run(os.Args[1],values)
    if err==nil { err=json.NewEncoder(os.Stdout).Encode(result) }
    if err!=nil { fmt.Fprintln(os.Stderr,err);os.Exit(1) }
}
