package dotnet

import (
	"fmt"
	"os"
	"path/filepath"
	"strings"

	"zlh-agent/internal/provision/executil"
	"zlh-agent/internal/provision/markers"
	"zlh-agent/internal/state"
)

func Install(cfg state.Config) error {
	marker := runtimeMarker(cfg.Version)
	if runtimeInstalled(cfg.Version) {
		if !markers.IsPresent(marker) {
			return markers.Write(marker)
		}
		return nil
	}
	if markers.IsPresent(marker) {
		return nil
	}

	if err := executil.RunEmbeddedScript(
		"devcontainer/dotnet/install.sh",
		"RUNTIME=dotnet",
		"ARCHIVE_EXT=tar.gz",
		"RUNTIME_VERSION="+cfg.Version,
	); err != nil {
		return fmt.Errorf("dotnet devcontainer install failed: %w", err)
	}

	return markers.Write(marker)
}

func runtimeInstalled(version string) bool {
	info, err := os.Stat(filepath.Join("/opt/zlh/runtimes/dotnet", strings.TrimSpace(version)))
	return err == nil && info.IsDir()
}

func runtimeMarker(version string) string {
	return "devcontainer-dotnet-" + strings.ReplaceAll(strings.TrimSpace(version), "/", "_")
}
