package models

import (
	"errors"
	"fmt"
	"os"
	"strconv"
	"strings"
)

type BinaryVersion struct {
	Major int
	Minor int
	Patch int
}

func ParseBinaryVersion(path string) (*BinaryVersion, error) {
	data, err := os.ReadFile(path)
	if err != nil {
		return nil, err
	}

	content := string(data)

	dashPos := strings.LastIndex(content, "-")
	if dashPos == -1 {
		return nil, errors.New("no dash found in version string")
	}

	start := dashPos - 6
	if start < 0 {
		start = 0
	}

	versionSlice := content[start:]
	end := strings.Index(versionSlice, "-")
	if end == -1 {
		end = len(versionSlice)
	}

	versionStr := versionSlice[:end]
	parts := strings.SplitN(versionStr, ".", 3)
	if len(parts) != 3 {
		return nil, errors.New("invalid version format")
	}

	major, err := strconv.Atoi(parts[0])
	if err != nil {
		return nil, err
	}
	minor, err := strconv.Atoi(parts[1])
	if err != nil {
		return nil, err
	}
	patch, err := strconv.Atoi(parts[2])
	if err != nil {
		return nil, err
	}

	return &BinaryVersion{major, minor, patch}, nil
}

func (v *BinaryVersion) String() string {
	return fmt.Sprintf("%d.%d.%d", v.Major, v.Minor, v.Patch)
}

func (v BinaryVersion) ToInt() int {
	return v.Major*100 + v.Minor*10 + v.Patch
}

func (v BinaryVersion) Subtract(other BinaryVersion) int {
	return v.ToInt() - other.ToInt()
}
