class_name PlantProvider extends WorkProvider
## WorkProvider for the "plant" work category.
##
## Scans World.crops for harvestable (READY) or sowable (TILLED) crops and
## returns the nearest suitable Job for the requesting pawn.
##
## Priority within plant work: harvest > sow.
##   A READY crop is always preferred over a TILLED one — getting food off the
##   plants before it is exposed to weather events matters more than replanting.
##   Harvest is checked first; sow is only attempted when no harvest work exists.
##
## Harvest Job (two toils):
##   walk_to(crop.tile) → interact(crop.get_path(), "on_harvest_tick")
##
## Sow Job (two toils — no seed cost, Rimworld-style):
##   walk_to(crop.tile) → interact(crop.get_path(), "on_sow_tick")
##   The designation alone triggers work; no grain is consumed.  on_sow_tick()
##   flips the crop from TILLED → SOWN so growth begins on the next sim tick.
##
## The INTERACT toil calls the action method once per sim tick.  Both actions
## complete in a single tick; the done-check in JobRunner._tick_interact fires
## after the call when is_harvestable() / is_sowable() returns false.
##
## Duck-typing note: Crop is referenced without explicit typing to avoid
## class_name registration-order issues at boot. We rely only on:
##   crop.tile: Vector2i
##   crop.is_harvestable() -> bool
##   crop.is_sowable() -> bool
##   crop.get_path() -> NodePath
##   crop.crop_kind: StringName


func _init() -> void:
	category = &"plant"
	# Above crafting (4) so READY crops get harvested before pawns disappear
	# into plank-crafting loops while wheat rots. Same tier as chop (5).
	priority = 5


## Returns the nearest READY-harvest Job, or — when none exist — the nearest
## sow Job, or null when no plant work is available.
## `pawn` is duck-typed: must expose .tile (Vector2i).
func find_best_for(pawn) -> Job:
	# ── 1. Harvest pass — always wins over sow ───────────────────────────────
	var j := _find_harvest(pawn)
	if j != null:
		return j

	# ── 2. Sow pass — only if no harvest work exists ─────────────────────────
	return _find_sow(pawn)


# ── private helpers ───────────────────────────────────────────────────────────

## Scan World.crops for the nearest harvestable (READY) crop and build a job.
## Returns null when nothing is ready.
func _find_harvest(pawn) -> Job:
	var best = null
	var best_dist: int = 999999

	for crop in World.crops:
		if not crop.is_harvestable():
			continue
		if Job.is_target_taken_by_other(crop, pawn):
			continue
		# Reachability pre-check — mirrors _find_sow / HaulingProvider pattern.
		if pawn.tile != crop.tile and World.pathfinder != null:
			if World.pathfinder.find_path(pawn.tile, crop.tile).is_empty():
				continue
		var d: int = abs(crop.tile.x - pawn.tile.x) + abs(crop.tile.y - pawn.tile.y)
		if d < best_dist:
			best_dist = d
			best = crop

	if best == null:
		return null

	var j := Job.new()
	j.label = "Harvest %s at %s" % [best.crop_kind, best.tile]
	j.target_node = best
	j.toils.append(Toil.walk_to(best.tile))
	j.toils.append(Toil.interact(best.get_path(), &"on_harvest_tick"))
	return j


## Scan World.crops for the nearest sowable (TILLED) crop and build a 2-toil
## sow job.  No seed item is consumed — sow is a free designation (Rimworld-style).
## Returns null when no sowable crop is reachable.
func _find_sow(pawn) -> Job:
	var best_crop = null
	var best_crop_dist: int = 999999

	for crop in World.crops:
		if not crop.is_sowable():
			continue
		if Job.is_target_taken_by_other(crop, pawn):
			continue
		# Reachability pre-check — mirrors HaulingProvider / EatProvider pattern.
		if pawn.tile != crop.tile and World.pathfinder != null:
			if World.pathfinder.find_path(pawn.tile, crop.tile).is_empty():
				continue
		var d: int = abs(crop.tile.x - pawn.tile.x) + abs(crop.tile.y - pawn.tile.y)
		if d < best_crop_dist:
			best_crop_dist = d
			best_crop = crop

	if best_crop == null:
		return null

	var j := Job.new()
	j.label = "Sow %s at %s" % [best_crop.crop_kind, best_crop.tile]
	j.target_node = best_crop
	j.toils.append(Toil.walk_to(best_crop.tile))
	j.toils.append(Toil.interact(best_crop.get_path(), &"on_sow_tick"))
	return j
