package ollama

import (
	"context"
	"fmt"
	"io"
	"net/http"
	"strings"

	runtime "iop/packages/go/execution"
)

func (o *Ollama) HandleCommand(ctx context.Context, req runtime.CommandRequest) (runtime.CommandResponse, error) {
	if req.Type != runtime.CommandTypeOllamaAPI {
		return runtime.CommandResponse{}, fmt.Errorf("ollama adapter: unsupported command %q", req.Type)
	}
	method := strings.ToUpper(strings.TrimSpace(req.Metadata["ollama_method"]))
	if method == "" {
		method = http.MethodGet
	}
	if method != http.MethodGet && method != http.MethodPost && method != http.MethodDelete {
		return runtime.CommandResponse{}, fmt.Errorf("ollama adapter: unsupported method %q", method)
	}
	path := strings.TrimSpace(req.Metadata["ollama_path"])
	if !strings.HasPrefix(path, "/api/") {
		return runtime.CommandResponse{}, fmt.Errorf("ollama adapter: unsupported path %q", path)
	}

	body := req.Metadata["ollama_body"]
	var reader io.Reader
	if body != "" {
		reader = strings.NewReader(body)
	}
	httpReq, err := http.NewRequestWithContext(ctx, method, joinURLRequestURI(o.baseURL, path), reader)
	if err != nil {
		return runtime.CommandResponse{}, fmt.Errorf("ollama adapter: build passthrough request: %w", err)
	}
	if body != "" {
		httpReq.Header.Set("Content-Type", "application/json")
	}
	resp, err := o.client.Do(httpReq)
	if err != nil {
		return runtime.CommandResponse{}, fmt.Errorf("ollama adapter: passthrough request: %w", err)
	}
	defer resp.Body.Close()

	return runtime.CommandResponse{
		RequestID: req.RequestID,
		Type:      req.Type,
		Adapter:   req.Adapter,
		Target:    req.Target,
		SessionID: req.SessionID,
		Result: map[string]string{
			"status_code":  fmt.Sprintf("%d", resp.StatusCode),
			"content_type": resp.Header.Get("Content-Type"),
			"body":         readLimited(resp.Body, 16<<20),
		},
	}, nil
}
