package minecraft

import (
	"fmt"
	"io"
	"net/http"
	"os"
	"path/filepath"

	"zlh-agent/internal/provcommon"
	"zlh-agent/internal/state"
)

func InstallMinecraftJar(cfg state.Config) error {
	dir := provcommon.ServerDir(cfg)
	if err := os.MkdirAll(dir, 0o755); err != nil {
		return fmt.Errorf("mkdir server dir: %w", err)
	}

	url := provcommon.BuildArtifactURL(cfg.ArtifactPath)
	dest := filepath.Join(dir, "server.jar")

	resp, err := http.Get(url)
	if err != nil {
		return fmt.Errorf("download server jar: %w", err)
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		return fmt.Errorf("bad status %s", resp.Status)
	}

	out, err := os.Create(dest)
	if err != nil {
		return fmt.Errorf("create server.jar: %w", err)
	}
	defer out.Close()

	if _, err := io.Copy(out, resp.Body); err != nil {
		return fmt.Errorf("write server.jar: %w", err)
	}

	if err := VerifyMinecraftInstallWithRepair(cfg); err != nil {
		return fmt.Errorf("jar install verification failed: %w", err)
	}

	return nil
}

func InstallFabric(cfg state.Config) error {
	if err := InstallMinecraftJar(cfg); err != nil {
		return fmt.Errorf("fabric install failed: %w", err)
	}
	return nil
}
