// Command update-client is a small, read-only example of consuming the public
// latest.json contract and verifying an artifact before making it available.
package main

import (
	"crypto/sha256"
	"encoding/hex"
	"encoding/json"
	"errors"
	"flag"
	"fmt"
	"io"
	"math"
	"net/http"
	"net/url"
	"os"
	"path/filepath"
	"regexp"
	"strconv"
	"strings"
	"time"
)

const maxManifestBytes = 1 << 20

var (
	versionPattern    = regexp.MustCompile(`^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(-([0-9A-Za-z.-]+))?(\+([0-9A-Za-z.-]+))?$`)
	numericPattern    = regexp.MustCompile(`^[0-9]+$`)
	filenamePattern   = regexp.MustCompile(`^[\p{L}\p{N}][\p{L}\p{N}._+-]{0,127}$`)
	identifierPattern = regexp.MustCompile(`^[a-z0-9][a-z0-9_-]{1,62}$`)
)

type updateManifest struct {
	SchemaVersion int    `json:"schemaVersion"`
	AppID         string `json:"appId"`
	Channel       string `json:"channel"`
	Platform      string `json:"platform"`
	Version       string `json:"version"`
	PublishedAt   string `json:"publishedAt"`
	DownloadURL   string `json:"downloadUrl"`
	Filename      string `json:"filename"`
	SizeBytes     int64  `json:"sizeBytes"`
	SHA256        string `json:"sha256"`
}

func main() {
	if err := run(); err != nil {
		fmt.Fprintln(os.Stderr, "update-client:", err)
		os.Exit(1)
	}
}

func run() error {
	return runWithArgs(os.Args[1:], os.Stdout, os.Stderr)
}

func runWithArgs(args []string, output, diagnostics io.Writer) error {
	return runWithHTTPClient(args, output, diagnostics, nil)
}

// runWithHTTPClient accepts an injected transport only for in-process tests.
// The normal CLI path passes nil and uses the default certificate-verified HTTPS client.
func runWithHTTPClient(args []string, output, diagnostics io.Writer, client *http.Client) error {
	flags := flag.NewFlagSet("update-client", flag.ContinueOnError)
	flags.SetOutput(diagnostics)
	manifestURL := flags.String("manifest", "", "HTTPS URL of the app's public latest.json")
	appID := flags.String("app-id", "", "expected application identifier")
	channel := flags.String("channel", "", "expected release channel")
	platform := flags.String("platform", "", "expected platform identifier")
	currentVersion := flags.String("current-version", "", "currently installed semantic version")
	allowPrerelease := flags.Bool("allow-prerelease", false, "allow downloading a newer prerelease version")
	outputPath := flags.String("out", "", "destination file for the verified artifact")
	timeout := flags.Duration("timeout", 15*time.Minute, "overall request timeout")
	maxBytes := flags.Int64("max-bytes", 10<<30, "maximum artifact size accepted")
	if err := flags.Parse(args); err != nil {
		if errors.Is(err, flag.ErrHelp) {
			return nil
		}
		return err
	}
	if flags.NArg() != 0 {
		return errors.New("unexpected positional arguments")
	}
	if *manifestURL == "" || *outputPath == "" || !identifierPattern.MatchString(*appID) ||
		!identifierPattern.MatchString(*channel) || !identifierPattern.MatchString(*platform) || *timeout <= 0 || *maxBytes <= 0 {
		return errors.New("-manifest, -app-id, -channel, -platform, -out, positive -timeout and positive -max-bytes are required")
	}
	if err := validateHTTPSURL(*manifestURL); err != nil {
		return fmt.Errorf("invalid manifest URL: %w", err)
	}
	if _, _, _, _, err := parseVersion(*currentVersion); err != nil {
		return errors.New("-current-version must be a valid semantic version")
	}

	if client == nil {
		client = newHTTPSClient(*timeout)
	}

	manifest, err := readManifest(client, *manifestURL)
	if err != nil {
		return err
	}
	if err := validateManifest(manifest, *maxBytes); err != nil {
		return fmt.Errorf("manifest rejected: %w", err)
	}
	if manifest.AppID != *appID || manifest.Channel != *channel || manifest.Platform != *platform {
		return errors.New("manifest application, channel, or platform does not match the requested target")
	}
	_, _, _, prerelease, _ := parseVersion(manifest.Version)
	if compareVersion(manifest.Version, *currentVersion) <= 0 {
		fmt.Fprintf(output, "no-update app=%s channel=%s platform=%s installed=%s latest=%s reason=installed_not_older\n",
			manifest.AppID, manifest.Channel, manifest.Platform, *currentVersion, manifest.Version)
		return nil
	}
	if prerelease != "" && !*allowPrerelease {
		fmt.Fprintf(output, "prerelease-skipped app=%s channel=%s platform=%s installed=%s latest=%s (pass -allow-prerelease to opt in)\n",
			manifest.AppID, manifest.Channel, manifest.Platform, *currentVersion, manifest.Version)
		return nil
	}

	outputPathAbs, err := filepath.Abs(*outputPath)
	if err != nil {
		return errors.New("output path is invalid")
	}
	actualDigest, err := downloadArtifact(client, manifest, outputPathAbs)
	if err != nil {
		return err
	}
	fmt.Fprintf(output, "verified app=%s channel=%s platform=%s version=%s sizeBytes=%d sha256=%s\n",
		manifest.AppID, manifest.Channel, manifest.Platform, manifest.Version, manifest.SizeBytes, actualDigest)
	return nil
}

func newHTTPSClient(timeout time.Duration) *http.Client {
	return &http.Client{
		Timeout: timeout,
		CheckRedirect: func(request *http.Request, via []*http.Request) error {
			if len(via) >= 5 {
				return errors.New("too many redirects")
			}
			if err := validateHTTPSURL(request.URL.String()); err != nil {
				return errors.New("redirect target must be HTTPS without credentials")
			}
			return nil
		},
	}
}

func downloadArtifact(client *http.Client, manifest updateManifest, outputPath string) (string, error) {
	if err := validateManifest(manifest, manifest.SizeBytes); err != nil {
		return "", fmt.Errorf("manifest rejected: %w", err)
	}
	if err := validateHTTPSURL(manifest.DownloadURL); err != nil {
		return "", errors.New("download URL must be HTTPS without embedded credentials")
	}
	if _, err := os.Lstat(outputPath); err == nil {
		return "", errors.New("output file already exists; choose another path")
	} else if !errors.Is(err, os.ErrNotExist) {
		return "", errors.New("output path cannot be inspected")
	}
	outputDir := filepath.Dir(outputPath)
	if err := os.MkdirAll(outputDir, 0o755); err != nil {
		return "", errors.New("output directory could not be created")
	}
	temporary, err := os.CreateTemp(outputDir, ".arkfor-update-*")
	if err != nil {
		return "", errors.New("temporary output file could not be created")
	}
	temporaryPath := temporary.Name()
	defer os.Remove(temporaryPath)

	request, err := http.NewRequest(http.MethodGet, manifest.DownloadURL, nil)
	if err != nil {
		_ = temporary.Close()
		return "", errors.New("download URL is invalid")
	}
	request.Header.Set("Accept", "application/octet-stream")
	response, err := client.Do(request)
	if err != nil {
		_ = temporary.Close()
		return "", errors.New("artifact download failed")
	}
	defer response.Body.Close()
	if response.StatusCode != http.StatusOK {
		_ = temporary.Close()
		return "", fmt.Errorf("artifact server returned HTTP %d", response.StatusCode)
	}

	hasher := sha256.New()
	limited := &io.LimitedReader{R: response.Body, N: manifest.SizeBytes + 1}
	written, copyErr := io.Copy(io.MultiWriter(temporary, hasher), limited)
	if copyErr != nil {
		_ = temporary.Close()
		return "", errors.New("artifact download was interrupted")
	}
	if written != manifest.SizeBytes {
		_ = temporary.Close()
		return "", errors.New("artifact size does not match the manifest")
	}
	actualDigest := hex.EncodeToString(hasher.Sum(nil))
	if !strings.EqualFold(actualDigest, manifest.SHA256) {
		_ = temporary.Close()
		return "", errors.New("artifact SHA-256 does not match the manifest")
	}
	if err := temporary.Sync(); err != nil {
		_ = temporary.Close()
		return "", errors.New("verified artifact could not be flushed to disk")
	}
	if err := temporary.Close(); err != nil {
		return "", errors.New("verified artifact could not be closed")
	}
	if err := os.Link(temporaryPath, outputPath); err != nil {
		return "", errors.New("verified artifact could not be written without replacing the destination")
	}
	return actualDigest, nil
}

func readManifest(client *http.Client, manifestURL string) (updateManifest, error) {
	request, err := http.NewRequest(http.MethodGet, manifestURL, nil)
	if err != nil {
		return updateManifest{}, errors.New("manifest request could not be created")
	}
	request.Header.Set("Accept", "application/json")
	response, err := client.Do(request)
	if err != nil {
		return updateManifest{}, errors.New("manifest request failed")
	}
	defer response.Body.Close()
	if response.StatusCode != http.StatusOK {
		return updateManifest{}, fmt.Errorf("manifest server returned HTTP %d", response.StatusCode)
	}
	body, err := io.ReadAll(io.LimitReader(response.Body, maxManifestBytes+1))
	if err != nil || len(body) > maxManifestBytes {
		return updateManifest{}, errors.New("manifest could not be read or is too large")
	}
	var manifest updateManifest
	if err := json.Unmarshal(body, &manifest); err != nil {
		return updateManifest{}, errors.New("manifest JSON is invalid")
	}
	return manifest, nil
}

func validateManifest(manifest updateManifest, maxBytes int64) error {
	if manifest.SchemaVersion != 1 || !identifierPattern.MatchString(manifest.AppID) ||
		!identifierPattern.MatchString(manifest.Channel) || !identifierPattern.MatchString(manifest.Platform) {
		return errors.New("schema or application target is unsupported")
	}
	if _, _, _, _, err := parseVersion(manifest.Version); err != nil {
		return errors.New("version is invalid")
	}
	if !validFilename(manifest.Filename) {
		return errors.New("filename is invalid")
	}
	if manifest.SizeBytes <= 0 || manifest.SizeBytes > maxBytes || manifest.SizeBytes == math.MaxInt64 {
		return errors.New("artifact size is outside the configured limit")
	}
	if len(manifest.SHA256) != sha256.Size*2 {
		return errors.New("SHA-256 is invalid")
	}
	if _, err := hex.DecodeString(manifest.SHA256); err != nil {
		return errors.New("SHA-256 is invalid")
	}
	if err := validateHTTPSURL(manifest.DownloadURL); err != nil {
		return errors.New("download URL must be HTTPS without embedded credentials")
	}
	if manifest.PublishedAt != "" {
		publishedAt, err := time.Parse(time.RFC3339Nano, manifest.PublishedAt)
		if err != nil {
			return errors.New("publishedAt is invalid")
		}
		_, offset := publishedAt.Zone()
		if offset != 0 {
			return errors.New("publishedAt must be UTC")
		}
	}
	return nil
}

// validFilename mirrors the server's manifest filename contract: Unicode letters
// and numbers are allowed so a release such as a Chinese-named package stays
// consumable, while path separators, spaces, a leading dot and overlong byte
// sequences (the filesystem component limit used by uploads) remain rejected.
func validFilename(name string) bool {
	return len(name) <= 200 && filenamePattern.MatchString(name)
}

func parseVersion(value string) (uint64, uint64, uint64, string, error) {
	match := versionPattern.FindStringSubmatch(value)
	if match == nil {
		return 0, 0, 0, "", errors.New("invalid semantic version")
	}
	major, err := strconv.ParseUint(match[1], 10, 64)
	if err != nil {
		return 0, 0, 0, "", err
	}
	minor, err := strconv.ParseUint(match[2], 10, 64)
	if err != nil {
		return 0, 0, 0, "", err
	}
	patch, err := strconv.ParseUint(match[3], 10, 64)
	if err != nil {
		return 0, 0, 0, "", err
	}
	prerelease, build := match[5], match[7]
	if prerelease != "" {
		if err := validateVersionIdentifiers(prerelease, true); err != nil {
			return 0, 0, 0, "", err
		}
	}
	if build != "" {
		if err := validateVersionIdentifiers(build, false); err != nil {
			return 0, 0, 0, "", err
		}
	}
	return major, minor, patch, prerelease, nil
}

func validateVersionIdentifiers(value string, rejectNumericLeadingZero bool) error {
	start := 0
	for start <= len(value) {
		end := strings.IndexByte(value[start:], '.')
		if end < 0 {
			end = len(value)
		} else {
			end += start
		}
		if end == start {
			return errors.New("empty semantic version identifier")
		}
		identifier := value[start:end]
		if rejectNumericLeadingZero && numericPattern.MatchString(identifier) && len(identifier) > 1 && identifier[0] == '0' {
			return errors.New("leading zero in numeric prerelease identifier")
		}
		if end == len(value) {
			return nil
		}
		start = end + 1
	}
	return errors.New("empty semantic version identifier")
}

func versionIdentifierEnd(value string, start int) int {
	separator := strings.IndexByte(value[start:], '.')
	if separator < 0 {
		return len(value)
	}
	return start + separator
}

func compareVersion(a, b string) int {
	aMajor, aMinor, aPatch, aPrerelease, aErr := parseVersion(a)
	bMajor, bMinor, bPatch, bPrerelease, bErr := parseVersion(b)
	if aErr != nil || bErr != nil {
		return strings.Compare(a, b)
	}
	for _, pair := range [][2]uint64{{aMajor, bMajor}, {aMinor, bMinor}, {aPatch, bPatch}} {
		if pair[0] < pair[1] {
			return -1
		}
		if pair[0] > pair[1] {
			return 1
		}
	}
	return comparePrerelease(aPrerelease, bPrerelease)
}

func comparePrerelease(a, b string) int {
	if a == b {
		return 0
	}
	if a == "" {
		return 1
	}
	if b == "" {
		return -1
	}
	aStart, bStart := 0, 0
	for {
		aEnd, bEnd := versionIdentifierEnd(a, aStart), versionIdentifierEnd(b, bStart)
		aIdentifier, bIdentifier := a[aStart:aEnd], b[bStart:bEnd]
		if aIdentifier != bIdentifier {
			aNumeric, bNumeric := numericPattern.MatchString(aIdentifier), numericPattern.MatchString(bIdentifier)
			if aNumeric && bNumeric {
				if len(aIdentifier) < len(bIdentifier) {
					return -1
				}
				if len(aIdentifier) > len(bIdentifier) {
					return 1
				}
				return strings.Compare(aIdentifier, bIdentifier)
			}
			if aNumeric {
				return -1
			}
			if bNumeric {
				return 1
			}
			return strings.Compare(aIdentifier, bIdentifier)
		}
		aFinished, bFinished := aEnd == len(a), bEnd == len(b)
		if aFinished || bFinished {
			switch {
			case aFinished && bFinished:
				return 0
			case aFinished:
				return -1
			default:
				return 1
			}
		}
		aStart, bStart = aEnd+1, bEnd+1
	}
}

func validateHTTPSURL(value string) error {
	parsed, err := url.ParseRequestURI(value)
	if err != nil || parsed.Scheme != "https" || parsed.Host == "" || parsed.User != nil {
		return errors.New("URL must use HTTPS and must not contain credentials")
	}
	return nil
}
