package naive

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

const githubAPILatest = "https://api.github.com/repos/klzgrad/naiveproxy/releases/latest"

// ResolveBinary finds naive.exe/naive in binDir or PATH.
func ResolveBinary(binDir string) (string, error) {
	name := "naive"
	if runtime.GOOS == "windows" {
		name = "naive.exe"
	}
	candidates := []string{
		filepath.Join(binDir, name),
		filepath.Join(binDir, "naiveproxy", name),
	}
	if exe, err := os.Executable(); err == nil {
		candidates = append(candidates, filepath.Join(filepath.Dir(exe), name))
		candidates = append(candidates, filepath.Join(filepath.Dir(exe), "bin", name))
	}
	for _, c := range candidates {
		if st, err := os.Stat(c); err == nil && !st.IsDir() {
			return c, nil
		}
	}
	return "", fmt.Errorf("naive binary not found (looked in %s); run: vpnclient install-core", binDir)
}

// EnsureBinary downloads the official Windows/Linux/macOS 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
	}
	pattern, err := assetNameForPlatform()
	if err != nil {
		return "", err
	}
	fmt.Fprintf(os.Stderr, "downloading official naiveproxy release (%s)...\n", pattern)
	assetName, url, err := findReleaseAsset(pattern)
	if err != nil {
		return "", err
	}
	zipPath := filepath.Join(binDir, assetName)
	if err := downloadFile(zipPath, url); err != nil {
		return "", err
	}
	defer os.Remove(zipPath)

	if err := unzipNaive(zipPath, binDir); err != nil {
		return "", err
	}
	return ResolveBinary(binDir)
}

func assetNameForPlatform() (string, error) {
	switch {
	case runtime.GOOS == "windows" && runtime.GOARCH == "amd64":
		return "naiveproxy-*-win-x64.zip", nil
	case runtime.GOOS == "windows" && runtime.GOARCH == "arm64":
		return "naiveproxy-*-win-arm64.zip", nil
	case runtime.GOOS == "linux" && runtime.GOARCH == "amd64":
		return "naiveproxy-*-linux-x64.zip", nil
	case runtime.GOOS == "darwin" && runtime.GOARCH == "amd64":
		return "naiveproxy-*-mac-x64.tar.xz", nil
	case runtime.GOOS == "darwin" && runtime.GOARCH == "arm64":
		return "naiveproxy-*-mac-arm64.tar.xz", nil
	default:
		return "", fmt.Errorf("unsupported platform %s/%s for auto-download; place naive binary in bin/", 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(pattern 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", "vpnclient-go")
	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
	}
	prefix := strings.Split(pattern, "*")[0]
	suffix := ""
	if parts := strings.Split(pattern, "*"); len(parts) == 2 {
		suffix = parts[1]
	}
	for _, a := range rel.Assets {
		if strings.HasPrefix(a.Name, prefix) && strings.HasSuffix(a.Name, suffix) {
			if strings.Contains(a.Name, ".tar.") {
				return "", "", fmt.Errorf("auto-extract of %s not implemented; download manually from %s", a.Name, a.BrowserDownloadURL)
			}
			return a.Name, a.BrowserDownloadURL, nil
		}
	}
	return "", "", fmt.Errorf("no asset matching %s in release %s", pattern, 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
}

func unzipNaive(zipPath, destDir string) error {
	r, err := zip.OpenReader(zipPath)
	if err != nil {
		return err
	}
	defer r.Close()

	want := "naive"
	if runtime.GOOS == "windows" {
		want = "naive.exe"
	}
	var found bool
	for _, f := range r.File {
		base := filepath.Base(f.Name)
		if base != want {
			continue
		}
		if err := extractFile(f, filepath.Join(destDir, want)); err != nil {
			return err
		}
		found = true
		break
	}
	if !found {
		return fmt.Errorf("zip does not contain %s", want)
	}
	return nil
}

func extractFile(f *zip.File, dest string) error {
	rc, err := f.Open()
	if err != nil {
		return err
	}
	defer rc.Close()
	out, err := os.OpenFile(dest, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o755)
	if err != nil {
		return err
	}
	defer out.Close()
	_, err = io.Copy(out, rc)
	return err
}
