package thb.jeanluc.adventure.model;

import lombok.Builder;
import lombok.Getter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * Non-player character. Talks via a fixed {@link #greeting} and may react
 * to items given to it through entries in {@link #reactions}.
 */
@Getter
@Builder
public class Npc {

    /** Unique identifier of this NPC, used for lookup and player input matching. */
    private final String id;

    /** Human-readable display name shown to the player. */
    private final String name;

    /** Long description shown by the {@code examine} command. */
    private final String description;

    /** Text the NPC says when talked to. */
    private final String greeting;

    /**
     * Reactions keyed by the trigger item's id. {@code HashMap} gives O(1)
     * lookup on {@code give X to Y}. The loader installs entries during
     * reference resolution after all items have been built.
     */
    private final Map<String, NpcReaction> reactions;

    /** Optional condition-gated dialogue lines, first match wins; else {@link #greeting}. */
    @Builder.Default
    private final List<DialogueLine> dialogue = new ArrayList<>();

    /**
     * Adds a conditional dialogue line.
     *
     * @param line the dialogue line
     */
    public void addDialogue(DialogueLine line) {
        dialogue.add(line);
    }

    /**
     * Looks up a reaction triggered by an item.
     *
     * @param itemId id of the item being offered
     * @return the matching reaction, or empty if the NPC does not react
     */
    public Optional<NpcReaction> reactionFor(String itemId) {
        return Optional.ofNullable(reactions.get(itemId));
    }

    /**
     * Convenience factory used by the loader before reactions are resolved.
     * Returns an NPC carrying a fresh, mutable reactions map.
     *
     * @param id          unique id
     * @param name        display name
     * @param description long description
     * @param greeting    greeting text
     * @return a new NPC shell
     */
    public static Npc shell(String id, String name, String description, String greeting) {
        return Npc.builder()
                .id(id)
                .name(name)
                .description(description)
                .greeting(greeting)
                .reactions(new HashMap<>())
                .build();
    }

    /**
     * Adds or replaces a reaction. Used by the loader during reference
     * resolution.
     *
     * @param triggerItemId id of the item that triggers the reaction
     * @param reaction      the reaction to attach
     */
    public void putReaction(String triggerItemId, NpcReaction reaction) {
        reactions.put(triggerItemId, reaction);
    }
}
