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 (four toils):
##   walk_to(grain_item.tile) → pickup → walk_to(crop.tile)
##       → interact(crop.get_path(), "on_sow_tick")
##   The grain item is consumed by the INTERACT completion (on_sow_tick does
##   the stage transition; the pawn's carried item is cleared by the provider
##   by queuing a DROP toil after interact, or — simpler — on_sow_tick itself
##   does not free the item, so we add a consume step here).
##
## Seed item: Item.TYPE_GRAIN (&"grain") — universal MVP seed for all crop kinds.
##   Wheat/corn already produce grain on harvest. Potato/strawberry accept grain
##   as seed in the same way (MVP simplification noted in design.md).
##
## 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 ─────────────────────────
	# Pawn must not already be carrying something (no double-carry).
	if pawn.carried_item != null:
		return null
	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
		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, find a reachable
## grain item to use as seed, and build a 4-toil sow job.
## Returns null when no sowable tile or no grain exists.
func _find_sow(pawn) -> Job:
	# Find the nearest sowable crop the pawn can reach.
	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

	# Find the nearest free grain item in the world.
	var best_grain = null
	var best_grain_dist: int = 999999

	for it in World.items:
		if it.item_type != Item.TYPE_GRAIN:
			continue
		if it.being_carried:
			continue
		# Reachability pre-check for the grain item too.
		if pawn.tile != it.tile and World.pathfinder != null:
			if World.pathfinder.find_path(pawn.tile, it.tile).is_empty():
				continue
		var d: int = abs(it.tile.x - pawn.tile.x) + abs(it.tile.y - pawn.tile.y)
		if d < best_grain_dist:
			best_grain_dist = d
			best_grain = it

	if best_grain == 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
	# Walk to the grain, pick it up, walk to the crop tile, sow.
	# on_sow_tick() transitions the crop TILLED → SOWN; after the interact toil
	# the pawn still carries the consumed grain.  A trailing DROP toil deposits
	# it at the pawn's current tile (which is the crop tile); the item simply
	# falls on the ground and HaulingProvider re-hauls it.  This is intentional
	# MVP behaviour — the player sees the seed "planted" and any excess grain is
	# returned to the floor for hauling. A future refinement can consume it
	# outright by adding a CONSUME toil kind to JobRunner.
	j.toils.append(Toil.walk_to(best_grain.tile))
	j.toils.append(Toil.pickup())
	j.toils.append(Toil.walk_to(best_crop.tile))
	j.toils.append(Toil.interact(best_crop.get_path(), &"on_sow_tick"))
	# Deposit the consumed grain at the crop tile so HaulingProvider can route
	# it back to a stockpile.  MVP simplification: the seed is not destroyed on
	# sow — it becomes a floor item.  A future CONSUME toil kind in JobRunner
	# would burn the item in-place without spawning a floor stack.
	j.toils.append(Toil.deposit())
	return j
