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.
##
## The returned Job is a two-toil sequence:
##   walk_to(crop.tile) → interact(crop.get_path(), "on_harvest_tick" | "on_sow_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 a Job targeting the nearest READY crop, or null when none are ready.
## `pawn` is duck-typed: must expose .tile (Vector2i).
##
## Phase 7 scope: harvest only. Sow work returns null (would loop infinitely
## with harvest at the same priority — pawns would never craft / cook).
## Phase 17 will add a separate SowProvider at a lower priority or expose
## sow as a player-designation flow.
func find_best_for(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
