package reconcile

import (
	"fmt"
	"sort"
	"strconv"
)

// ActionKind is the benign-on-existing-guest action set wired in slice 4. The
// destructive set (guest destroy, storage wipe, restore-overwrite, decommission) is
// classified and gated in Phase B but not represented here — nothing serves
// destructive deltas until slice 10.
type ActionKind string

const (
	// ActionStart powers on a stopped guest (proxmox VM.PowerMgmt).
	ActionStart ActionKind = "start"
	// ActionStop powers off a running guest (proxmox VM.PowerMgmt).
	ActionStop ActionKind = "stop"
	// ActionSetConfig applies benign config changes (cores/memory/description) in one
	// PUT (proxmox VM.Config.*). May return synchronously (empty UPID) — slice-4 proven.
	ActionSetConfig ActionKind = "set_config"
	// ActionResize GROWS the rootfs (proxmox `pct resize`, async). Grow-only — the planner
	// emits it only when desired DiskBytes > actual; a shrink is data-losing and is refused
	// (never silently applied as a grow). Slice 5 Phase B; unfed live until slice 10.
	ActionResize ActionKind = "resize"
	// ActionDecommission tears a guest down — the canonical DESTRUCTIVE delta (slice 10A). The
	// planner emits it for an explicit DesiredGuest.Decommission; it classifies ClassDecommission
	// → Destructive, so the gate refuses it `pending_signature` (no signer in 10A → never
	// executed). Its EXECUTOR is slice 10B; 10A only plans + gates it.
	ActionDecommission ActionKind = "decommission"
)

// growRoundMiB rounds a positive byte delta UP to whole MiB for the Proxmox `+<n>M` grow
// size (Proxmox resizes in whole units; rounding up never under-provisions the desired size).
func growRoundMiB(deltaBytes int64) int64 {
	return (deltaBytes + bytesPerMiB - 1) / bytesPerMiB
}

// Action is one minimal mutation the engine will dispatch onto the per-guest queue.
// In Phase A every Action is benign by construction (only the benign kinds exist).
// Phase B's classifier/gate sits in front of the executor and may tag an action
// destructive (requiring a signature) without changing this shape.
type Action struct {
	VMID   int
	Kind   ActionKind
	Params map[string]string // non-nil only for ActionSetConfig
	Reason string            // human/debug: why this action was planned
}

// bytesPerMiB converts the desired-spec MemoryBytes (hub.GuestSpec is in bytes) to
// the MiB unit Proxmox's LXC `memory` config field uses.
const bytesPerMiB = 1024 * 1024

// desiredMemoryMiB canonicalizes a desired byte count to the integer MiB that
// Proxmox's `memory` field stores and reports. Floor division is deliberate and
// convergent: the value returned here is exactly the value written via SetConfig, so a
// subsequent read returns the same MiB and the comparison settles (see Plan's memory
// note). The actual side (a.MemoryMiB) is already MiB from GuestConfig.
func desiredMemoryMiB(bytes int64) int64 { return bytes / bytesPerMiB }

// Plan computes the minimal benign action set converging actual → desired. It is a
// pure function (deterministic, side-effect-free) so it is exhaustively fixture-test
// -able. Actions are returned sorted by vmid, then config-before-runstate per guest.
//
// Scope rules (slice 4):
//   - Only guests present in BOTH desired and actual are reconciled. A guest desired
//     but absent from actual would be PROVISIONING (restore-to-new-guest, slice 7) —
//     skipped here. A guest actual but not desired would be a DESTROY (destructive,
//     gated, slice 10) — skipped here.
//   - Unmanaged desired fields (RunUnspecified / nil Spec / nil Description) produce
//     no action.
//   - If actual spec is unknown (GuestConfig read failed), spec/description are not
//     compared (run-state still is) — we never write a config we couldn't read first.
//   - Comparisons are NORMALIZED (description trailing-newline, etc.) so a faithful
//     round-trip is not mistaken for drift.
func Plan(desired DesiredState, actual ActualState, norm FieldNormalizers) []Action {
	if norm == nil {
		norm = DefaultNormalizers()
	}
	vmids := make([]int, 0, len(desired.Guests))
	for vmid := range desired.Guests {
		vmids = append(vmids, vmid)
	}
	sort.Ints(vmids)

	var actions []Action
	for _, vmid := range vmids {
		d := desired.Guests[vmid]
		a, ok := actual.Guests[vmid]
		if !ok {
			// Desired but not present: provisioning (slice 7), not a slice-4 action.
			continue
		}

		// EXPLICIT decommission (slice 10A) — the destructive delta. Emit it as a single
		// ActionDecommission and emit NOTHING else for this guest (no point reconciling cores
		// on a guest the operator wants torn down). It is classified Destructive downstream, so
		// the gate refuses it pending_signature in 10A (executor is 10B). Only emitted when the
		// guest actually exists (decommissioning an absent guest is a no-op).
		if d.Decommission {
			actions = append(actions, Action{
				VMID:   vmid,
				Kind:   ActionDecommission,
				Reason: "decommission requested (destructive — requires operator signature)",
			})
			continue
		}

		// Benign spec/description changes → a single SetConfig, only when we could
		// read the current config (else we'd write blind).
		if a.SpecKnown {
			params := map[string]string{}
			var reasons []string
			if d.Spec != nil {
				if d.Spec.Cores != a.Cores {
					params["cores"] = strconv.Itoa(d.Spec.Cores)
					reasons = append(reasons, fmt.Sprintf("cores %d->%d", a.Cores, d.Spec.Cores))
				}
				// Memory is canonicalized to MiB on BOTH sides before comparison — the
				// numeric cousin of the description-newline normalization (string
				// normalizers cover string fields; this is the integer one). We compare
				// the SAME MiB value we then write, so a non-MiB-aligned desired
				// converges in one pass (write `want` MiB → PVE stores `want` MiB → next
				// read a.MemoryMiB == want → no further action), never perpetual drift.
				// Slice 10 should still serve MiB-aligned MemoryBytes at the source.
				if want := desiredMemoryMiB(d.Spec.MemoryBytes); want != a.MemoryMiB {
					params["memory"] = strconv.FormatInt(want, 10)
					reasons = append(reasons, fmt.Sprintf("memory %dMiB->%dMiB", a.MemoryMiB, want))
				}
			}
			// Rootfs GROW (slice 5 Phase B) — a separate async op from the config PUT, so
			// its own Action. GROW-ONLY: emit a resize only when desired > actual. A shrink
			// (desired < actual) is data-losing and is REFUSED here — we never silently
			// clamp it to a grow; it is simply not planned (a deliberate shrink would have
			// to come as a signed destructive op, slice 10). DiskBytes==0 means unmanaged.
			if d.Spec != nil && d.Spec.DiskBytes > 0 && a.DiskBytes > 0 {
				switch {
				case d.Spec.DiskBytes > a.DiskBytes:
					deltaMiB := growRoundMiB(d.Spec.DiskBytes - a.DiskBytes)
					actions = append(actions, Action{
						VMID:   vmid,
						Kind:   ActionResize,
						Params: map[string]string{"disk": "rootfs", "size": fmt.Sprintf("+%dM", deltaMiB)},
						Reason: fmt.Sprintf("disk grow %dB->%dB (+%dMiB)", a.DiskBytes, d.Spec.DiskBytes, deltaMiB),
					})
				case d.Spec.DiskBytes < a.DiskBytes:
					// Shrink refused by omission: emit NO action (a data-losing shrink is a
					// signed destructive op, slice 10 — never a benign reconcile grow). The
					// executor also guards (size must start with '+'). See the resize note above.
				}
			}
			if d.Description != nil && !norm.Equal("description", *d.Description, a.Description) {
				params["description"] = *d.Description
				reasons = append(reasons, "description")
			}
			if len(params) > 0 {
				actions = append(actions, Action{
					VMID:   vmid,
					Kind:   ActionSetConfig,
					Params: params,
					Reason: "spec drift: " + join(reasons),
				})
			}
		}

		// Run-state (Start/Stop) — always comparable from the list status.
		if d.Run != RunUnspecified && d.Run != a.Run {
			switch d.Run {
			case RunRunning:
				actions = append(actions, Action{VMID: vmid, Kind: ActionStart,
					Reason: fmt.Sprintf("run %q->running", a.Run)})
			case RunStopped:
				actions = append(actions, Action{VMID: vmid, Kind: ActionStop,
					Reason: fmt.Sprintf("run %q->stopped", a.Run)})
			}
		}
	}
	return actions
}

func join(parts []string) string {
	out := ""
	for i, p := range parts {
		if i > 0 {
			out += ", "
		}
		out += p
	}
	return out
}
