// Package network provides networking and server communication utilities
package network

import (
	"fmt"
)

// MLServer wraps SSHClient to provide a high-level interface for ML operations.
// It consolidates the TUI and worker implementations into a single reusable component.
type MLServer struct {
	client SSHClient
	addr   string
}

// NewMLServer creates a new ML server connection.
// If host is empty, it creates a local mode client (no SSH).
func NewMLServer(host, user, sshKey string, port int, knownHosts string) (*MLServer, error) {
	// Local mode: skip SSH entirely
	if host == "" {
		client, _ := NewSSHClient("", "", "", 0, "")
		return &MLServer{client: *client, addr: "localhost"}, nil
	}

	client, err := NewSSHClient(host, user, sshKey, port, knownHosts)
	if err != nil {
		return nil, fmt.Errorf("failed to create SSH client: %w", err)
	}

	addr := fmt.Sprintf("%s:%d", host, port)
	return &MLServer{client: *client, addr: addr}, nil
}

// Exec executes a command on the ML server.
// For local mode, it executes directly on the local machine.
func (s *MLServer) Exec(command string) (string, error) {
	return s.client.Exec(command)
}

// ListDir lists files in a directory on the ML server.
func (s *MLServer) ListDir(path string) []string {
	return s.client.ListDir(path)
}

// Addr returns the server address ("localhost" for local mode).
func (s *MLServer) Addr() string {
	return s.addr
}

// IsLocal returns true if running in local mode (no SSH).
func (s *MLServer) IsLocal() bool {
	return s.addr == "localhost"
}

// Close closes the SSH connection.
func (s *MLServer) Close() error {
	return s.client.Close()
}
