using Theriapolis.Core.Data;
using Theriapolis.Core.Tactical;

namespace Theriapolis.Core.Rules.Combat;

/// <summary>
/// Maps a <see cref="TacticalSpawn"/> + chunk's <see cref="TacticalChunk.DangerZone"/>
/// to the actual <see cref="NpcTemplateDef"/> that should spawn there.
/// Lookup table lives in <c>npc_templates.json</c>'s
/// <c>spawn_kind_to_template_by_zone</c> map (loaded into
/// <see cref="NpcTemplateContent.SpawnKindToTemplateByZone"/>).
///
/// Returns null when no template is configured for the spawn kind/zone (the
/// caller should skip that spawn — chunk is silently denser, that's OK).
/// </summary>
public static class NpcInstantiator
{
    public static NpcTemplateDef? PickTemplate(
        SpawnKind kind,
        int dangerZone,
        NpcTemplateContent content)
    {
        if (kind == SpawnKind.None) return null;
        string kindKey = kind.ToString();
        if (!content.SpawnKindToTemplateByZone.TryGetValue(kindKey, out var byZone))
            return null;
        if (byZone.Length == 0) return null;
        // Clamp the zone index to the table's length.
        int zoneIdx = System.Math.Clamp(dangerZone, 0, byZone.Length - 1);
        string templateId = byZone[zoneIdx];
        foreach (var t in content.Templates)
            if (string.Equals(t.Id, templateId, System.StringComparison.OrdinalIgnoreCase))
                return t;
        return null;
    }
}
