package hysteria2

import (
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"os"
	"path/filepath"
	"runtime"
	"strings"
	"time"
)

const githubAPILatest = "https://api.github.com/repos/apernet/hysteria/releases/latest"

// ResolveBinary finds hysteria client binary.
func ResolveBinary(binDir string) (string, error) {
	names := candidateNames()
	candidates := []string{}
	for _, name := range names {
		candidates = append(candidates,
			filepath.Join(binDir, name),
			filepath.Join(binDir, "hysteria2", name),
			filepath.Join(binDir, "hysteria", name),
		)
	}
	if exe, err := os.Executable(); err == nil {
		dir := filepath.Dir(exe)
		for _, name := range names {
			candidates = append(candidates, filepath.Join(dir, name), filepath.Join(dir, "bin", name))
		}
	}
	for _, c := range candidates {
		if st, err := os.Stat(c); err == nil && !st.IsDir() {
			return c, nil
		}
	}
	return "", fmt.Errorf("hysteria2 binary not found in %s; run install-core", binDir)
}

func candidateNames() []string {
	if runtime.GOOS == "windows" {
		return []string{
			"hysteria.exe",
			"hysteria-windows-amd64.exe",
			"hysteria-windows-amd64-avx.exe",
		}
	}
	return []string{"hysteria", "hysteria-linux-amd64"}
}

// EnsureBinary downloads official Hysteria 2 release if missing.
func EnsureBinary(binDir string) (string, error) {
	if path, err := ResolveBinary(binDir); err == nil {
		return path, nil
	}
	if err := os.MkdirAll(binDir, 0o755); err != nil {
		return "", err
	}
	want, err := releaseAssetName()
	if err != nil {
		return "", err
	}
	fmt.Fprintf(os.Stderr, "downloading official hysteria2 release (%s)...\n", want)
	name, url, err := findReleaseAsset(want)
	if err != nil {
		return "", err
	}
	destName := "hysteria"
	if runtime.GOOS == "windows" {
		destName = "hysteria.exe"
	}
	dest := filepath.Join(binDir, destName)
	tmp := filepath.Join(binDir, name+".download")
	if err := downloadFile(tmp, url); err != nil {
		return "", err
	}
	_ = os.Remove(dest)
	if err := os.Rename(tmp, dest); err != nil {
		_ = os.Remove(tmp)
		return "", err
	}
	_ = os.Chmod(dest, 0o755)
	return ResolveBinary(binDir)
}

func releaseAssetName() (string, error) {
	switch {
	case runtime.GOOS == "windows" && runtime.GOARCH == "amd64":
		return "hysteria-windows-amd64.exe", nil
	case runtime.GOOS == "windows" && runtime.GOARCH == "arm64":
		return "hysteria-windows-arm64.exe", nil
	case runtime.GOOS == "linux" && runtime.GOARCH == "amd64":
		return "hysteria-linux-amd64", nil
	case runtime.GOOS == "darwin" && runtime.GOARCH == "amd64":
		return "hysteria-darwin-amd64", nil
	case runtime.GOOS == "darwin" && runtime.GOARCH == "arm64":
		return "hysteria-darwin-arm64", nil
	default:
		return "", fmt.Errorf("unsupported platform %s/%s for hysteria2 auto-download", runtime.GOOS, runtime.GOARCH)
	}
}

type ghRelease struct {
	TagName string `json:"tag_name"`
	Assets  []struct {
		Name               string `json:"name"`
		BrowserDownloadURL string `json:"browser_download_url"`
	} `json:"assets"`
}

func findReleaseAsset(exactName string) (name, downloadURL string, err error) {
	client := &http.Client{Timeout: 60 * time.Second}
	req, err := http.NewRequest(http.MethodGet, githubAPILatest, nil)
	if err != nil {
		return "", "", err
	}
	req.Header.Set("Accept", "application/vnd.github+json")
	req.Header.Set("User-Agent", "navis-vpnclient")
	resp, err := client.Do(req)
	if err != nil {
		return "", "", fmt.Errorf("github api: %w", err)
	}
	defer resp.Body.Close()
	if resp.StatusCode != http.StatusOK {
		body, _ := io.ReadAll(io.LimitReader(resp.Body, 512))
		return "", "", fmt.Errorf("github api: %s: %s", resp.Status, string(body))
	}
	var rel ghRelease
	if err := json.NewDecoder(resp.Body).Decode(&rel); err != nil {
		return "", "", err
	}
	// Prefer exact non-avx name; fall back to avx variant on Windows.
	var fallback string
	var fallbackURL string
	for _, a := range rel.Assets {
		if a.Name == exactName {
			return a.Name, a.BrowserDownloadURL, nil
		}
		if exactName == "hysteria-windows-amd64.exe" && a.Name == "hysteria-windows-amd64-avx.exe" {
			fallback, fallbackURL = a.Name, a.BrowserDownloadURL
		}
	}
	if fallback != "" {
		return fallback, fallbackURL, nil
	}
	// Prefix match for versioned names
	for _, a := range rel.Assets {
		if strings.HasPrefix(a.Name, strings.TrimSuffix(exactName, filepath.Ext(exactName))) {
			return a.Name, a.BrowserDownloadURL, nil
		}
	}
	return "", "", fmt.Errorf("no asset %s in release %s", exactName, rel.TagName)
}

func downloadFile(path, url string) error {
	client := &http.Client{Timeout: 10 * time.Minute}
	resp, err := client.Get(url)
	if err != nil {
		return err
	}
	defer resp.Body.Close()
	if resp.StatusCode != http.StatusOK {
		return fmt.Errorf("download %s: %s", url, resp.Status)
	}
	f, err := os.Create(path)
	if err != nil {
		return err
	}
	defer f.Close()
	_, err = io.Copy(f, resp.Body)
	return err
}
