package cli

import (
	"context"
	"errors"
	"fmt"
	"io"
	"os"
	"os/exec"
	"strings"
	"time"

	"iop/apps/node/internal/runtime"
	"iop/packages/go/config"
)

func (c *CLI) executeOneShot(ctx context.Context, spec runtime.ExecutionSpec, profile config.CLIProfileConf, sink runtime.EventSink) error {
	prompt := extractPrompt(spec.Input)
	args := append(append([]string{}, profile.Args...), prompt)
	_, err := c.executeCommand(ctx, spec, profile, args, prompt, sink)
	return err
}

func (c *CLI) executeCommand(ctx context.Context, spec runtime.ExecutionSpec, profile config.CLIProfileConf, args []string, prompt string, sink runtime.EventSink) (string, error) {
	cmd := exec.CommandContext(ctx, profile.Command, args...)

	if len(profile.Env) > 0 {
		cmd.Env = append(cmd.Environ(), profile.Env...)
	}

	stdout, err := cmd.StdoutPipe()
	if err != nil {
		return "", fmt.Errorf("cli adapter: stdout pipe: %w", err)
	}
	stderr, err := cmd.StderrPipe()
	if err != nil {
		return "", fmt.Errorf("cli adapter: stderr pipe: %w", err)
	}

	if err := cmd.Start(); err != nil {
		return "", fmt.Errorf("cli adapter: start %q: %w", profile.Command, err)
	}

	_ = sink.Emit(ctx, runtime.RuntimeEvent{
		RunID:     spec.RunID,
		Type:      runtime.EventTypeStart,
		Timestamp: time.Now(),
	})

	var errBuf strings.Builder
	var outBuf strings.Builder
	combinedOutput := func() string {
		return outBuf.String() + errBuf.String()
	}
	stderrDone := make(chan error, 1)
	go func() {
		_, err := io.Copy(&errBuf, stderr)
		stderrDone <- err
	}()

	var (
		outputTokens int
		readErr      error
	)
	if reg, ok := jsonEmitters[profile.OutputFormat]; ok {
		outputTokens, readErr = driveJSONLines(ctx, stdout, sink, spec.RunID, &outBuf, reg.emitter, reg.scanBufMax)
	} else {
		outputTokens, readErr = emitStdoutChunks(ctx, stdout, sink, spec.RunID, &outBuf)
	}
	if readErr != nil {
		_ = <-stderrDone
		_ = cmd.Wait()
		_ = sink.Emit(ctx, runtime.RuntimeEvent{
			RunID:     spec.RunID,
			Type:      runtime.EventTypeError,
			Error:     fmt.Sprintf("read stdout: %v", readErr),
			Timestamp: time.Now(),
		})
		return combinedOutput(), fmt.Errorf("cli adapter: read stdout: %w", readErr)
	}

	waitErr := cmd.Wait()
	stderrErr := <-stderrDone
	if waitErr != nil {
		if ctx.Err() != nil {
			_ = sink.Emit(context.Background(), runtime.RuntimeEvent{
				RunID:     spec.RunID,
				Type:      runtime.EventTypeCancelled,
				Message:   cancelEventForContext(ctx.Err()),
				Timestamp: time.Now(),
			})
			return combinedOutput(), runtime.ErrRunCancelled
		}
		_ = sink.Emit(ctx, runtime.RuntimeEvent{
			RunID:     spec.RunID,
			Type:      runtime.EventTypeError,
			Error:     fmt.Sprintf("command failed: %v — %s", waitErr, errBuf.String()),
			Timestamp: time.Now(),
		})
		return combinedOutput(), fmt.Errorf("cli adapter: command exited with error: %w", waitErr)
	}
	if stderrErr != nil && !errors.Is(stderrErr, os.ErrClosed) {
		_ = sink.Emit(ctx, runtime.RuntimeEvent{
			RunID:     spec.RunID,
			Type:      runtime.EventTypeError,
			Error:     fmt.Sprintf("read stderr: %v", stderrErr),
			Timestamp: time.Now(),
		})
		return combinedOutput(), fmt.Errorf("cli adapter: read stderr: %w", stderrErr)
	}

	return combinedOutput(), sink.Emit(ctx, runtime.RuntimeEvent{
		RunID:   spec.RunID,
		Type:    runtime.EventTypeComplete,
		Message: "cli execution complete",
		Usage: &runtime.UsageStats{
			InputTokens:  len(strings.Fields(prompt)),
			OutputTokens: outputTokens,
		},
		Timestamp: time.Now(),
	})
}

func emitStdoutChunks(ctx context.Context, stdout io.Reader, sink runtime.EventSink, runID string, outBuf *strings.Builder) (int, error) {
	buf := make([]byte, 4096)
	outputTokens := 0

	for {
		n, err := stdout.Read(buf)
		if n > 0 {
			delta := string(buf[:n])
			outBuf.WriteString(delta)
			outputTokens += len(strings.Fields(delta))
			_ = sink.Emit(ctx, runtime.RuntimeEvent{
				RunID:     runID,
				Type:      runtime.EventTypeDelta,
				Delta:     delta,
				Timestamp: time.Now(),
			})
		}
		if errors.Is(err, io.EOF) {
			return outputTokens, nil
		}
		if err != nil {
			return outputTokens, err
		}
	}
}

func extractPrompt(input map[string]any) string {
	if input == nil {
		return ""
	}
	if v, ok := input["prompt"]; ok {
		if s, ok := v.(string); ok {
			return s
		}
	}
	return fmt.Sprintf("%v", input)
}
