// NKSC1-c8c7ea42327292095dea8150adbebc85-0708f3a4174e426d0d2ad28718b26adb4894e3d58893d8e7340ae63a514fbf41

package license

import (
	"crypto/ed25519"
	"crypto/rand"
	"crypto/sha256"
	"encoding/hex"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"os"
	"path/filepath"
	"runtime"
	"strings"
	"sync"

	"wa-assistant/backend/config"
)

type deviceState struct {
	Version    int                 `json:"version"`
	Machine    string              `json:"machine"`
	Hardware   string              `json:"hardware"`
	Seed       []byte              `json:"seed"`
	Counter    uint64              `json:"counter"`
	LastSeenAt int64               `json:"last_seen_at"`
	RetryAfter int64               `json:"retry_after"`
	Lease      SignedChatLoopLease `json:"lease"`
}

// Outside the install directory: copying an application folder does not copy
// its private device key. Only tests replace these functions in memory.
var deviceStateRoot = func() (string, error) {
	root, err := os.UserConfigDir()
	if err != nil {
		return "", err
	}
	return filepath.Join(root, "ChatLoop", "Security"), nil
}
var deviceHardwareID = platformHardwareID

var runtimeLockMu sync.Mutex
var runtimeLock *os.File
var runtimeLockPath string

func acquireDeviceRuntime(machine string) error {
	runtimeLockMu.Lock()
	defer runtimeLockMu.Unlock()
	root, err := deviceStateRoot()
	if err != nil {
		return err
	}
	if err := os.MkdirAll(root, 0o700); err != nil {
		return err
	}
	path := filepath.Join(root, machine+".runtime.lock")
	if runtimeLock != nil {
		if runtimeLockPath == path {
			return nil
		}
		return errors.New("identitas instalasi berubah saat aplikasi berjalan")
	}
	file, err := os.OpenFile(path, os.O_CREATE|os.O_RDWR, 0o600)
	if err != nil {
		return err
	}
	if err := lockDeviceFile(file); err != nil {
		_ = file.Close()
		return errors.New("instalasi ini sudah berjalan; tutup salinan aplikasi terlebih dahulu")
	}
	runtimeLock, runtimeLockPath = file, path
	return nil
}

func releaseDeviceRuntime() {
	runtimeLockMu.Lock()
	defer runtimeLockMu.Unlock()
	if runtimeLock != nil {
		unlockDeviceFile(runtimeLock)
		_ = runtimeLock.Close()
		runtimeLock = nil
		runtimeLockPath = ""
	}
}

func hardwareFingerprint() (string, error) {
	id, err := deviceHardwareID()
	id = strings.TrimSpace(id)
	if err != nil || len(id) < 16 {
		return "", errors.New("ID sistem operasi tidak tersedia")
	}
	hash := sha256.Sum256([]byte("chatloop-hardware-v1|" + runtime.GOOS + "|" + strings.ToLower(id)))
	return hex.EncodeToString(hash[:]), nil
}

func withDeviceState(machine, hardware string, fn func(*deviceState, func() error) error) error {
	root, err := deviceStateRoot()
	if err != nil {
		return err
	}
	if err := os.MkdirAll(root, 0o700); err != nil {
		return err
	}
	if err := os.Chmod(root, 0o700); err != nil {
		return err
	}
	identityPath, err := filepath.Abs(config.Env("LICENSE_MACHINE_ID_PATH", "data/.license-machine-id"))
	if err != nil {
		return err
	}
	if resolved, err := filepath.EvalSymlinks(identityPath); err == nil {
		identityPath = resolved
	}
	// Windows updates retain the launcher-owned identity path in AppData. On
	// VPS, copying the install folder creates a different key-storage slot.
	slot := sha256.Sum256([]byte(machine + "|" + filepath.Clean(identityPath)))
	path := filepath.Join(root, hex.EncodeToString(slot[:])+".json")
	lock, err := os.OpenFile(path+".lock", os.O_CREATE|os.O_RDWR, 0o600)
	if err != nil {
		return err
	}
	defer lock.Close()
	if err := lockDeviceFile(lock); err != nil {
		return errors.New("instalasi ini sedang dipakai proses lain; tutup salinan aplikasi lalu coba kembali")
	}
	defer unlockDeviceFile(lock)
	state := deviceState{Version: 1, Machine: machine, Hardware: hardware}
	file, err := os.Open(path)
	if err == nil {
		data, readErr := io.ReadAll(io.LimitReader(file, (64<<10)+1))
		_ = file.Close()
		if readErr != nil || len(data) > 64<<10 {
			return errors.New("penyimpanan identitas rusak")
		}
		plain, err := unprotectDeviceState(data, machine)
		if err != nil {
			return errors.New("identitas bukan milik pengguna/perangkat ini atau rusak; gunakan pemindahan perangkat di LMS")
		}
		if err := json.Unmarshal(plain, &state); err != nil {
			return errors.New("format identitas perangkat tidak valid")
		}
		if state.Version != 1 || state.Machine != machine || state.Hardware != hardware || len(state.Seed) != ed25519.SeedSize {
			return errors.New("identitas tersalin dari perangkat lain; gunakan pemindahan perangkat di LMS")
		}
	} else if errors.Is(err, os.ErrNotExist) {
		state.Seed = make([]byte, ed25519.SeedSize)
		if _, err := rand.Read(state.Seed); err != nil {
			return err
		}
	} else {
		return err
	}
	save := func() error {
		data, err := json.Marshal(state)
		if err != nil {
			return err
		}
		protected, err := protectDeviceState(data, machine)
		if err != nil {
			return err
		}
		return writeDeviceState(path, protected)
	}
	return fn(&state, save)
}

func writeDeviceState(path string, data []byte) error {
	file, err := os.CreateTemp(filepath.Dir(path), ".device-*.tmp")
	if err != nil {
		return err
	}
	defer os.Remove(file.Name())
	defer file.Close()
	if err := file.Chmod(0o600); err != nil {
		return err
	}
	if _, err := file.Write(data); err != nil {
		return err
	}
	if err := file.Sync(); err != nil {
		return err
	}
	if err := file.Close(); err != nil {
		return err
	}
	if err := os.Rename(file.Name(), path); err != nil {
		return fmt.Errorf("menyimpan identitas: %w", err)
	}
	return nil
}
