package infra

import (
	"bytes"
	"context"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"strings"
	"time"
)

// DockerExecOpts configura la ejecucion de un comando dentro de un container Docker.
type DockerExecOpts struct {
	ContainerID     string   // ID o nombre del container destino.
	Cmd             []string // argv. Cmd[0] = binario, debe estar en BinariesAllowed.
	BinariesAllowed []string // Whitelist de binarios permitidos. EMPTY = rechaza todo.
	User            string   // Usuario/grupo "UID:GID"; vacio = default del container.
	WorkingDir      string   // Directorio de trabajo dentro del container.
	Env             []string // Variables de entorno en formato "KEY=VAL".
	TimeoutSeconds  int      // Timeout de ejecucion; default 30 si es 0.
	DockerHost      string   // Socket Docker; default "unix:///var/run/docker.sock".
}

// DockerExecResult contiene el resultado de ejecutar un comando en un container.
type DockerExecResult struct {
	ExitCode int    // Codigo de salida del proceso.
	Stdout   string // Salida estandar capturada.
	Stderr   string // Salida de error capturada.
	Duration int64  // Duracion real de ejecucion en milisegundos.
}

// DockerContainerExec ejecuta un comando dentro de un container Docker via Engine API.
//
// Flujo: POST /containers/<id>/exec → POST /exec/<id>/start → demux stream → GET /exec/<id>/json.
// El comando se pasa como argv directo (sin shell). Aplica whitelist obligatoria de binarios.
// Timeout gestionado via context.WithTimeout.
func DockerContainerExec(opts DockerExecOpts) (DockerExecResult, error) {
	// --- Validacion de seguridad (prioritaria, antes de contactar el engine) ---
	if len(opts.Cmd) == 0 {
		return DockerExecResult{}, fmt.Errorf("docker exec: Cmd must not be empty")
	}
	if len(opts.BinariesAllowed) == 0 {
		return DockerExecResult{}, fmt.Errorf("docker exec: no binaries whitelisted: refusing")
	}
	bin := opts.Cmd[0]
	inWhitelist := false
	for _, b := range opts.BinariesAllowed {
		if b == bin {
			inWhitelist = true
			break
		}
	}
	if !inWhitelist {
		return DockerExecResult{}, fmt.Errorf("docker exec: binary %q not in whitelist %v", bin, opts.BinariesAllowed)
	}
	if opts.ContainerID == "" {
		return DockerExecResult{}, fmt.Errorf("docker exec: ContainerID must not be empty")
	}

	// --- Defaults ---
	timeout := opts.TimeoutSeconds
	if timeout <= 0 {
		timeout = 30
	}

	ctx, cancel := context.WithTimeout(context.Background(), time.Duration(timeout)*time.Second)
	defer cancel()

	// Reuse dockerHTTPClient from docker_container_logs.go (same package).
	client, baseURL, err := dockerHTTPClient(opts.DockerHost)
	if err != nil {
		return DockerExecResult{}, fmt.Errorf("docker exec: building client: %w", err)
	}

	start := time.Now()

	// --- Step 1: Create exec instance ---
	execID, err := dockerExecCreate(ctx, client, baseURL, opts)
	if err != nil {
		return DockerExecResult{}, fmt.Errorf("docker exec create: %w", err)
	}

	// --- Step 2: Start exec and capture stream ---
	stdout, stderr, err := dockerExecStart(ctx, client, baseURL, execID)
	if err != nil {
		return DockerExecResult{}, fmt.Errorf("docker exec start: %w", err)
	}

	// --- Step 3: Inspect to get exit code ---
	exitCode, err := dockerExecInspect(ctx, client, baseURL, execID)
	if err != nil {
		return DockerExecResult{}, fmt.Errorf("docker exec inspect: %w", err)
	}

	duration := time.Since(start).Milliseconds()

	return DockerExecResult{
		ExitCode: exitCode,
		Stdout:   stdout,
		Stderr:   stderr,
		Duration: duration,
	}, nil
}

// dockerExecCreate llama POST /containers/<id>/exec y devuelve el ExecID.
func dockerExecCreate(ctx context.Context, client *http.Client, baseURL string, opts DockerExecOpts) (string, error) {
	type createBody struct {
		AttachStdout bool     `json:"AttachStdout"`
		AttachStderr bool     `json:"AttachStderr"`
		Tty          bool     `json:"Tty"`
		Cmd          []string `json:"Cmd"`
		User         string   `json:"User,omitempty"`
		WorkingDir   string   `json:"WorkingDir,omitempty"`
		Env          []string `json:"Env,omitempty"`
	}

	body := createBody{
		AttachStdout: true,
		AttachStderr: true,
		Tty:          false,
		Cmd:          opts.Cmd,
		User:         opts.User,
		WorkingDir:   opts.WorkingDir,
		Env:          opts.Env,
	}

	bodyBytes, err := json.Marshal(body)
	if err != nil {
		return "", err
	}

	url := fmt.Sprintf("%s/containers/%s/exec", baseURL, opts.ContainerID)
	req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(bodyBytes))
	if err != nil {
		return "", err
	}
	req.Header.Set("Content-Type", "application/json")

	resp, err := client.Do(req)
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusCreated {
		b, _ := io.ReadAll(io.LimitReader(resp.Body, 512))
		return "", fmt.Errorf("engine returned %d: %s", resp.StatusCode, strings.TrimSpace(string(b)))
	}

	var result struct {
		ID string `json:"Id"`
	}
	if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
		return "", err
	}
	if result.ID == "" {
		return "", fmt.Errorf("engine returned empty exec ID")
	}

	return result.ID, nil
}

// dockerExecStart llama POST /exec/<id>/start y demux el stream multiplexado de Docker.
// Reusa dockerDemuxFrame de docker_container_logs.go (mismo paquete).
// Retorna (stdout, stderr, error).
func dockerExecStart(ctx context.Context, client *http.Client, baseURL, execID string) (string, string, error) {
	type startBody struct {
		Detach bool `json:"Detach"`
		Tty    bool `json:"Tty"`
	}
	bodyBytes, _ := json.Marshal(startBody{Detach: false, Tty: false})

	url := fmt.Sprintf("%s/exec/%s/start", baseURL, execID)
	req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(bodyBytes))
	if err != nil {
		return "", "", err
	}
	req.Header.Set("Content-Type", "application/json")

	resp, err := client.Do(req)
	if err != nil {
		if ctx.Err() != nil {
			return "", "", fmt.Errorf("docker exec timed out")
		}
		return "", "", err
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		b, _ := io.ReadAll(io.LimitReader(resp.Body, 512))
		return "", "", fmt.Errorf("engine returned %d on start: %s", resp.StatusCode, strings.TrimSpace(string(b)))
	}

	// Demux usando dockerDemuxFrame de docker_container_logs.go.
	var stdoutBuf, stderrBuf strings.Builder
	for {
		streamType, payload, err := dockerDemuxFrame(resp.Body)
		if err == io.EOF {
			break
		}
		if err != nil {
			if ctx.Err() != nil {
				return "", "", fmt.Errorf("docker exec timed out")
			}
			return "", "", fmt.Errorf("reading exec stream: %w", err)
		}
		switch streamType {
		case 1: // stdout
			stdoutBuf.Write(payload)
		case 2: // stderr
			stderrBuf.Write(payload)
		}
	}

	return stdoutBuf.String(), stderrBuf.String(), nil
}

// dockerExecInspect llama GET /exec/<id>/json y devuelve el ExitCode.
func dockerExecInspect(ctx context.Context, client *http.Client, baseURL, execID string) (int, error) {
	url := fmt.Sprintf("%s/exec/%s/json", baseURL, execID)
	req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
	if err != nil {
		return -1, err
	}

	resp, err := client.Do(req)
	if err != nil {
		return -1, err
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		b, _ := io.ReadAll(io.LimitReader(resp.Body, 512))
		return -1, fmt.Errorf("engine returned %d on inspect: %s", resp.StatusCode, strings.TrimSpace(string(b)))
	}

	var result struct {
		ExitCode int `json:"ExitCode"`
	}
	if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
		return -1, err
	}

	return result.ExitCode, nil
}
