package host

import (
	"context"
	"time"
)

// HostBackend defines the interface for command execution and file system
// operations. Implementations include DirectBackend (host OS), WSLBackend
// (Windows Subsystem for Linux), and DockerBackend (container).
type HostBackend interface {
	Exec(ctx context.Context, command, workDir string, timeout time.Duration) (*ExecResult, error)
	ReadFile(path string, maxBytes int) (string, error)
	WriteFile(path, content string, maxBytes int) error
	ListDir(path string) ([]DirEntry, error)
	SystemInfo() map[string]interface{}
	DiskUsage(path string) (map[string]interface{}, error)
	Name() string
}

// Manager provides controlled access to the host machine. It delegates
// to a HostBackend implementation which may be direct, WSL, or Docker.
type Manager struct {
	backend HostBackend
}

// NewManager creates a new host Manager with the given backend.
func NewManager(backend HostBackend) *Manager {
	return &Manager{backend: backend}
}

// SetAllowedDirs updates directory restrictions. Only effective for
// DirectBackend; WSL and Docker backends are no-ops.
func (m *Manager) SetAllowedDirs(dirs []string) {
	if db, ok := m.backend.(*DirectBackend); ok {
		db.SetAllowedDirs(dirs)
	}
}

// Exec runs a command via the configured backend.
func (m *Manager) Exec(ctx context.Context, command, workDir string, timeout time.Duration) (*ExecResult, error) {
	return m.backend.Exec(ctx, command, workDir, timeout)
}

// ReadFile reads a file via the configured backend.
func (m *Manager) ReadFile(path string, maxBytes int) (string, error) {
	return m.backend.ReadFile(path, maxBytes)
}

// WriteFile writes a file via the configured backend.
func (m *Manager) WriteFile(path, content string, maxBytes int) error {
	return m.backend.WriteFile(path, content, maxBytes)
}

// ListDir lists a directory via the configured backend.
func (m *Manager) ListDir(path string) ([]DirEntry, error) {
	return m.backend.ListDir(path)
}

// SystemInfo returns system information from the configured backend.
func (m *Manager) SystemInfo() map[string]interface{} {
	return m.backend.SystemInfo()
}

// DiskUsage returns disk usage info from the configured backend.
func (m *Manager) DiskUsage(path string) (map[string]interface{}, error) {
	return m.backend.DiskUsage(path)
}

// BackendName returns the name of the active backend.
func (m *Manager) BackendName() string {
	return m.backend.Name()
}
