package config

import (
	"os"
	"strconv"
	"time"
)

// HCFSConfig holds configuration for HCFS integration
type HCFSConfig struct {
	// API settings
	APIURL     string `yaml:"api_url" json:"api_url"`
	APITimeout time.Duration `yaml:"api_timeout" json:"api_timeout"`
	
	// Workspace settings
	MountPath        string        `yaml:"mount_path" json:"mount_path"`
	WorkspaceTimeout time.Duration `yaml:"workspace_timeout" json:"workspace_timeout"`
	
	// FUSE settings
	FUSEEnabled    bool   `yaml:"fuse_enabled" json:"fuse_enabled"`
	FUSEMountPoint string `yaml:"fuse_mount_point" json:"fuse_mount_point"`
	
	// Cleanup settings
	IdleCleanupInterval time.Duration `yaml:"idle_cleanup_interval" json:"idle_cleanup_interval"`
	MaxIdleTime         time.Duration `yaml:"max_idle_time" json:"max_idle_time"`
	
	// Storage settings
	StoreArtifacts    bool `yaml:"store_artifacts" json:"store_artifacts"`
	CompressArtifacts bool `yaml:"compress_artifacts" json:"compress_artifacts"`
}

// NewHCFSConfig creates a new HCFS configuration with defaults
func NewHCFSConfig() *HCFSConfig {
	return &HCFSConfig{
		APIURL:              getEnvString("HCFS_API_URL", "http://localhost:8000"),
		APITimeout:          getEnvDuration("HCFS_API_TIMEOUT", 30*time.Second),
		MountPath:           getEnvString("HCFS_MOUNT_PATH", "/tmp/hcfs-workspaces"),
		WorkspaceTimeout:    getEnvDuration("HCFS_WORKSPACE_TIMEOUT", 2*time.Hour),
		FUSEEnabled:         getEnvBool("HCFS_FUSE_ENABLED", false),
		FUSEMountPoint:      getEnvString("HCFS_FUSE_MOUNT_POINT", "/mnt/hcfs"),
		IdleCleanupInterval: getEnvDuration("HCFS_IDLE_CLEANUP_INTERVAL", 15*time.Minute),
		MaxIdleTime:         getEnvDuration("HCFS_MAX_IDLE_TIME", 1*time.Hour),
		StoreArtifacts:      getEnvBool("HCFS_STORE_ARTIFACTS", true),
		CompressArtifacts:   getEnvBool("HCFS_COMPRESS_ARTIFACTS", false),
	}
}

// IsEnabled returns true if HCFS integration is enabled
func (c *HCFSConfig) IsEnabled() bool {
	return c.APIURL != "" && c.APIURL != "disabled"
}

// getEnvString gets a string environment variable with a default value
func getEnvString(key, defaultValue string) string {
	if value := os.Getenv(key); value != "" {
		return value
	}
	return defaultValue
}

// getEnvBool gets a boolean environment variable with a default value
func getEnvBool(key string, defaultValue bool) bool {
	if value := os.Getenv(key); value != "" {
		if parsed, err := strconv.ParseBool(value); err == nil {
			return parsed
		}
	}
	return defaultValue
}

// getEnvDuration gets a duration environment variable with a default value
func getEnvDuration(key string, defaultValue time.Duration) time.Duration {
	if value := os.Getenv(key); value != "" {
		if parsed, err := time.ParseDuration(value); err == nil {
			return parsed
		}
	}
	return defaultValue
}