package license

import (
	"crypto/ed25519"
	"crypto/rand"
	"crypto/sha256"
	"encoding/base64"
	"encoding/hex"
	"encoding/json"
	"net/http"
	"net/http/httptest"
	"os"
	"path/filepath"
	"strings"
	"sync"
	"testing"
	"time"
)

type leaseFixture struct {
	mu       sync.Mutex
	calls    int
	status   int
	mutate   func(*ChatLoopLease)
	unsigned bool
	signer   ed25519.PrivateKey
	server   *httptest.Server
}

func setupLeaseFixture(t *testing.T) *leaseFixture {
	t.Helper()
	pub, priv, err := ed25519.GenerateKey(rand.Reader)
	if err != nil {
		t.Fatal(err)
	}
	oldURL, oldKey, oldRoot, oldHW := PinnedLicenseAPIURL, PinnedLicenseSigningPublicKey, deviceStateRoot, deviceHardwareID
	root := t.TempDir()
	deviceStateRoot = func() (string, error) { return filepath.Join(root, "protected"), nil }
	deviceHardwareID = func() (string, error) { return "synthetic-hardware-original", nil }
	PinnedLicenseSigningPublicKey = base64.RawStdEncoding.EncodeToString(pub)
	t.Setenv("LICENSE_MACHINE_ID_PATH", filepath.Join(root, "app", ".license-machine-id"))
	t.Setenv("LICENSE_KEY", "WA-SYNTHETIC-LEASE-TEST")
	setVerificationState(false, "", "", "")
	f := &leaseFixture{signer: priv, status: 200}
	f.server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		f.mu.Lock()
		defer f.mu.Unlock()
		f.calls++
		if r.URL.Path != "/api/license/v3/verify" {
			t.Errorf("unexpected endpoint %s", r.URL.Path)
		}
		if f.status != 200 {
			w.WriteHeader(f.status)
			return
		}
		var req ChatLoopLicenseRequest
		if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
			t.Error(err)
			w.WriteHeader(400)
			return
		}
		public, _ := base64.RawStdEncoding.DecodeString(req.DevicePublicKey)
		proof, _ := base64.RawStdEncoding.DecodeString(req.Proof)
		if len(public) != ed25519.PublicKeySize || !ed25519.Verify(public, deviceProofBytes(req), proof) {
			t.Error("invalid client proof")
			w.WriteHeader(422)
			return
		}
		now := time.Now()
		digest := sha256.Sum256([]byte(req.LicenseKey))
		lease := ChatLoopLease{Version: 3, LicenseKeyHash: hex.EncodeToString(digest[:]), MachineHash: req.MachineHash,
			HardwareFingerprint: req.HardwareFingerprint, DevicePublicKey: req.DevicePublicKey, RequestNonce: req.Nonce, Counter: req.Counter,
			IssuedAt: now.Unix(), RefreshAfter: now.Add(12 * time.Hour).Unix(), ExpiresAt: now.Add(48 * time.Hour).Unix(),
			Valid: true, Status: StatusActive, ProductCode: "chatloop", Entitlements: []string{"runtime"}, PackageType: "pro", MachineMax: 3, Message: "OK"}
		if f.mutate != nil {
			f.mutate(&lease)
		}
		envelope := f.sign(lease)
		if f.unsigned {
			envelope.Signature = ""
		}
		_ = json.NewEncoder(w).Encode(successWrapper{Success: true, Data: &envelope})
	}))
	PinnedLicenseAPIURL = f.server.URL
	t.Cleanup(func() {
		releaseDeviceRuntime()
		f.server.Close()
		PinnedLicenseAPIURL, PinnedLicenseSigningPublicKey, deviceStateRoot, deviceHardwareID = oldURL, oldKey, oldRoot, oldHW
		setVerificationState(false, "", "", "")
	})
	return f
}
func (f *leaseFixture) sign(p ChatLoopLease) SignedChatLoopLease {
	raw, _ := json.Marshal(p)
	id := sha256.Sum256(f.signer.Public().(ed25519.PublicKey))
	return SignedChatLoopLease{Payload: raw, Signature: base64.RawStdEncoding.EncodeToString(ed25519.Sign(f.signer, raw)), KeyID: hex.EncodeToString(id[:8])}
}
func (f *leaseFixture) changeCache(t *testing.T, fn func(*deviceState, *ChatLoopLease)) {
	t.Helper()
	machine, _, err := machineFingerprints()
	if err != nil {
		t.Fatal(err)
	}
	hardware, err := hardwareFingerprint()
	if err != nil {
		t.Fatal(err)
	}
	if err := withDeviceState(machine, hardware, func(state *deviceState, save func() error) error {
		var p ChatLoopLease
		if err := json.Unmarshal(state.Lease.Payload, &p); err != nil {
			return err
		}
		fn(state, &p)
		state.Lease = f.sign(p)
		return save()
	}); err != nil {
		t.Fatal(err)
	}
}
func (f *leaseFixture) renewNow(t *testing.T) {
	f.changeCache(t, func(_ *deviceState, p *ChatLoopLease) {
		p.IssuedAt = time.Now().Add(-13 * time.Hour).Unix()
		p.RefreshAfter = time.Now().Add(-time.Hour).Unix()
		p.ExpiresAt = time.Now().Add(24 * time.Hour).Unix()
	})
}
func TestSignedLeaseReusesCacheAcrossRestartAndHeartbeats(t *testing.T) {
	f := setupLeaseFixture(t)
	if !Verify() {
		t.Fatalf("initial activation: %s", VerifyMessage)
	}
	setVerificationState(false, "", "", "")
	for i := 0; i < 10; i++ {
		if !Heartbeat() {
			t.Fatalf("cached verification %d: %s", i, VerifyMessage)
		}
	}
	f.mu.Lock()
	defer f.mu.Unlock()
	if f.calls != 1 {
		t.Fatalf("LMS calls=%d want 1", f.calls)
	}
}
func TestLeaseTrustCannotBeReplacedByMemberEnvironment(t *testing.T) {
	f := setupLeaseFixture(t)
	t.Setenv("LICENSE_API_URL", "http://127.0.0.1:1")
	t.Setenv("LICENSE_RESPONSE_SIGNING_PUBLIC_KEY", "bogus")
	if !Verify() {
		t.Fatalf("member env changed embedded trust: %s", VerifyMessage)
	}
	PinnedLicenseSigningPublicKey = ""
	if Verify() {
		t.Fatal("empty embedded key accepted")
	}
	f.mu.Lock()
	defer f.mu.Unlock()
	if f.calls != 1 {
		t.Fatal("missing trust key should fail before network")
	}
}
func TestLeaseRejectsUnsignedTamperedReplayedAndWrongIdentity(t *testing.T) {
	cases := map[string]func(*ChatLoopLease){
		"nonce":           func(p *ChatLoopLease) { p.RequestNonce = "replayed" },
		"counter":         func(p *ChatLoopLease) { p.Counter++ },
		"machine":         func(p *ChatLoopLease) { p.MachineHash = "another-machine" },
		"hardware":        func(p *ChatLoopLease) { p.HardwareFingerprint = "another-hardware" },
		"device_key":      func(p *ChatLoopLease) { p.DevicePublicKey = "another-key" },
		"license_key":     func(p *ChatLoopLease) { p.LicenseKeyHash = strings.Repeat("0", 64) },
		"product":         func(p *ChatLoopLease) { p.ProductCode = "kula_pos" },
		"entitlement":     func(p *ChatLoopLease) { p.Entitlements = []string{"source_code"} },
		"unbounded_grace": func(p *ChatLoopLease) { p.ExpiresAt = time.Now().Add(365 * 24 * time.Hour).Unix() },
		"expired":         func(p *ChatLoopLease) { p.ExpiresAt = time.Now().Add(-time.Minute).Unix() },
		"future":          func(p *ChatLoopLease) { p.IssuedAt = time.Now().Add(time.Hour).Unix() },
	}
	for name, mutate := range cases {
		t.Run(name, func(t *testing.T) {
			f := setupLeaseFixture(t)
			f.mutate = mutate
			if Verify() {
				t.Fatal("invalid signed lease accepted")
			}
		})
	}
	t.Run("unsigned", func(t *testing.T) {
		f := setupLeaseFixture(t)
		f.unsigned = true
		if Verify() {
			t.Fatal("unsigned response accepted")
		}
	})
	t.Run("tampered_cache", func(t *testing.T) {
		f := setupLeaseFixture(t)
		if !Verify() {
			t.Fatal(VerifyMessage)
		}
		machine, _, _ := machineFingerprints()
		hardware, _ := hardwareFingerprint()
		if err := withDeviceState(machine, hardware, func(s *deviceState, save func() error) error {
			s.Lease.Payload = []byte(strings.Replace(string(s.Lease.Payload), `"pro"`, `"unlimited"`, 1))
			return save()
		}); err != nil {
			t.Fatal(err)
		}
		f.mu.Lock()
		f.status = 503
		f.mu.Unlock()
		if Heartbeat() {
			t.Fatal("tampered cache accepted during outage")
		}
	})
}
func TestLeaseOutageGraceIsSignedBoundedAndRetriesAreLimited(t *testing.T) {
	f := setupLeaseFixture(t)
	if !Verify() {
		t.Fatal(VerifyMessage)
	}
	f.renewNow(t)
	f.mu.Lock()
	f.status = 503
	f.mu.Unlock()
	for i := 0; i < 10; i++ {
		if !Heartbeat() {
			t.Fatalf("valid offline lease rejected: %s", VerifyMessage)
		}
	}
	f.mu.Lock()
	calls := f.calls
	f.mu.Unlock()
	if calls != 2 {
		t.Fatalf("outage caused %d calls", calls)
	}
	t.Setenv("LICENSE_OFFLINE_GRACE_HOURS", "8760")
	f.changeCache(t, func(_ *deviceState, p *ChatLoopLease) {
		p.IssuedAt = time.Now().Add(-49 * time.Hour).Unix()
		p.RefreshAfter = p.IssuedAt + 3600
		p.ExpiresAt = time.Now().Add(-time.Hour).Unix()
	})
	if Heartbeat() {
		t.Fatal("expired lease extended by member env")
	}
}
func TestEverySignedDenialStopsAndRemovesOfflineLease(t *testing.T) {
	for _, status := range []string{"revoked", "deployment_conflict", "product_mismatch", "entitlement_missing", "device_key_mismatch", "device_proof_replayed", "future_denial_status"} {
		t.Run(status, func(t *testing.T) {
			f := setupLeaseFixture(t)
			if !Verify() {
				t.Fatal(VerifyMessage)
			}
			f.renewNow(t)
			f.mu.Lock()
			f.mutate = func(p *ChatLoopLease) { p.Valid = false; p.Status = status; p.Message = "denied" }
			f.mu.Unlock()
			if Heartbeat() {
				t.Fatal("signed denial tolerated")
			}
			f.mu.Lock()
			f.status = 503
			f.mu.Unlock()
			if Verify() {
				t.Fatal("revoked cached lease resurrected on restart")
			}
		})
	}
}
func TestCopiedInstallationHasNoUsableDeviceKeyOrLease(t *testing.T) {
	f := setupLeaseFixture(t)
	if !Verify() {
		t.Fatal(VerifyMessage)
	}
	deviceHardwareID = func() (string, error) { return "synthetic-other-hardware", nil }
	if Verify() {
		t.Fatal("copied protected identity accepted on different hardware")
	}
	f.mu.Lock()
	defer f.mu.Unlock()
	if f.calls != 1 {
		t.Fatal("hardware mismatch should fail locally")
	}
}
func TestLeaseRejectsClockRollbackDuringOutage(t *testing.T) {
	f := setupLeaseFixture(t)
	if !Verify() {
		t.Fatal(VerifyMessage)
	}
	f.changeCache(t, func(s *deviceState, _ *ChatLoopLease) { s.LastSeenAt = time.Now().Add(time.Hour).Unix() })
	f.mu.Lock()
	f.status = 503
	f.mu.Unlock()
	if Heartbeat() {
		t.Fatal("rollback accepted while offline")
	}
}
func TestMachineFingerprintRemainsStableForMigration(t *testing.T) {
	setupLeaseFixture(t)
	first, legacy, err := machineFingerprints()
	if err != nil {
		t.Fatal(err)
	}
	second, _, err := machineFingerprints()
	if err != nil || first != second || first == legacy {
		t.Fatal("unstable migration identity")
	}
	info, err := os.Stat(os.Getenv("LICENSE_MACHINE_ID_PATH"))
	if err != nil {
		t.Fatal(err)
	}
	if info.Mode().Perm() != 0o600 && os.PathSeparator != '\\' {
		t.Fatal("insecure identity permissions")
	}
}
func TestDeviceResetRequiresOwnerAccount(t *testing.T) {
	t.Setenv("LICENSE_PUBLIC_RESET_ENABLED", "true")
	if Reset() == nil {
		t.Fatal("public reset enabled by member env")
	}
}

func TestRuntimeLockRejectsSecondProcessHandle(t *testing.T) {
	setupLeaseFixture(t)
	machine, _, err := machineFingerprints()
	if err != nil {
		t.Fatal(err)
	}
	if err := acquireDeviceRuntime(machine); err != nil {
		t.Fatal(err)
	}
	root, _ := deviceStateRoot()
	file, err := os.OpenFile(filepath.Join(root, machine+".runtime.lock"), os.O_RDWR, 0600)
	if err != nil {
		t.Fatal(err)
	}
	defer file.Close()
	if err := lockDeviceFile(file); err == nil {
		unlockDeviceFile(file)
		t.Fatal("second handle acquired active installation lock")
	}
	releaseDeviceRuntime()
	if err := lockDeviceFile(file); err != nil {
		t.Fatalf("released lock unusable: %v", err)
	}
	unlockDeviceFile(file)
}

func TestCopiedInstallFolderDoesNotReusePrivateDeviceKey(t *testing.T) {
	setupLeaseFixture(t)
	machine, _, _ := machineFingerprints()
	hardware, _ := hardwareFingerprint()
	var firstSeed string
	if err := withDeviceState(machine, hardware, func(s *deviceState, save func() error) error {
		firstSeed = base64.RawStdEncoding.EncodeToString(s.Seed)
		return save()
	}); err != nil {
		t.Fatal(err)
	}
	t.Setenv("LICENSE_MACHINE_ID_PATH", filepath.Join(t.TempDir(), "copied", ".license-machine-id"))
	if err := withDeviceState(machine, hardware, func(s *deviceState, save func() error) error {
		if base64.RawStdEncoding.EncodeToString(s.Seed) == firstSeed {
			t.Fatal("copied path reused private key")
		}
		return save()
	}); err != nil {
		t.Fatal(err)
	}
}

func TestNetworkRetryBackoffSurvivesProcessRestart(t *testing.T) {
	f := setupLeaseFixture(t)
	if !Verify() {
		t.Fatal(VerifyMessage)
	}
	f.renewNow(t)
	f.mu.Lock()
	f.status = 503
	f.mu.Unlock()
	if !Heartbeat() {
		t.Fatal(VerifyMessage)
	}
	setVerificationState(false, "", "", "")
	releaseDeviceRuntime()
	if !Verify() {
		t.Fatal(VerifyMessage)
	}
	f.mu.Lock()
	defer f.mu.Unlock()
	if f.calls != 2 {
		t.Fatalf("restart caused request storm: calls=%d", f.calls)
	}
}
