// EchoAgent is a minimal ACP agent that echoes back user messages.
// Run: go run ./examples/echo_agent/main.go
// Then pipe a JSON-RPC initialize + session/new + session/prompt sequence to test.
package main

import (
	"context"
	"log"

	"github.com/keepmind9/acp-sdk-go/agent"
	"github.com/keepmind9/acp-sdk-go/helpers"
	"github.com/keepmind9/acp-sdk-go/schema"
)

func ptrSessionId(s string) *schema.SessionId              { v := schema.SessionId(s); return &v }
func ptrStopReason(s schema.StopReason) *schema.StopReason { return &s }

type echoAgent struct {
	conn *agent.AgentSideConnection
}

func main() {
	impl := &echoAgent{}
	impl.run()
}

func (a *echoAgent) run() {}

func (a *echoAgent) OnConnect(conn *agent.AgentSideConnection) {
	a.conn = conn
}

func (a *echoAgent) Initialize(_ context.Context, req *schema.InitializeRequest) (*schema.InitializeResponse, error) {
	protoVers := 1
	return &schema.InitializeResponse{
		ProtocolVersion:   &protoVers,
		AgentCapabilities: &schema.AgentCapabilities{},
		AgentInfo:         &schema.Implementation{Name: "echo-agent", Version: "0.1.0"},
	}, nil
}

func (a *echoAgent) Authenticate(_ context.Context, req *schema.AuthenticateRequest) (*schema.AuthenticateResponse, error) {
	return &schema.AuthenticateResponse{}, nil
}

func (a *echoAgent) NewSession(_ context.Context, req *schema.NewSessionRequest) (*schema.NewSessionResponse, error) {
	log.Printf("new_session: cwd=%s", req.Cwd)
	return &schema.NewSessionResponse{
		SessionId: ptrSessionId("sess-0"),
	}, nil
}

func (a *echoAgent) LoadSession(_ context.Context, req *schema.LoadSessionRequest) (*schema.LoadSessionResponse, error) {
	return &schema.LoadSessionResponse{}, nil
}

func (a *echoAgent) ListSessions(_ context.Context, req *schema.ListSessionsRequest) (*schema.ListSessionsResponse, error) {
	return &schema.ListSessionsResponse{}, nil
}

func (a *echoAgent) Prompt(_ context.Context, req *schema.PromptRequest) (*schema.PromptResponse, error) {
	for _, block := range req.Prompt {
		if block.Text != nil {
			log.Printf("echo: %s", block.Text.Text)
			update := helpers.AgentMessageUpdate(block.Text.Text)
			a.conn.SessionUpdate(*req.SessionId, &update)
		}
	}
	return &schema.PromptResponse{StopReason: ptrStopReason(schema.StopReasonEndTurn)}, nil
}

func (a *echoAgent) Cancel(_ context.Context, notif *schema.CancelNotification) error {
	log.Printf("cancel: session=%s", *notif.SessionId)
	return nil
}

func (a *echoAgent) SetSessionMode(_ context.Context, req *schema.SetSessionModeRequest) (*schema.SetSessionModeResponse, error) {
	return &schema.SetSessionModeResponse{}, nil
}

func (a *echoAgent) SetSessionConfigOption(_ context.Context, req *schema.SetSessionConfigOptionRequest) (*schema.SetSessionConfigOptionResponse, error) {
	return &schema.SetSessionConfigOptionResponse{}, nil
}
