-- lua/autorun/server/mrp_jailer_spawns.lua
if not SERVER then return end

local function SpawnJailers()
    -- Remove existing jailers to prevent duplicates on lua refresh
    for _, ent in ipairs(ents.FindByClass("rhc_jailer_rf")) do ent:Remove() end
    for _, ent in ipairs(ents.FindByClass("rhc_jailer_uk")) do ent:Remove() end

    -- Spawn RF Jailer
    local rf_jailer = ents.Create("rhc_jailer_rf")
    if IsValid(rf_jailer) then
        rf_jailer:SetPos(Vector(10651.541992, 10210.736328, 193.868973))
        rf_jailer:SetAngles(Angle(0, 90, 0))
        rf_jailer:Spawn()
        
        -- Drop to floor to be safe
        local tr = util.TraceLine({
            start = rf_jailer:GetPos() + Vector(0,0,10),
            endpos = rf_jailer:GetPos() - Vector(0,0,100),
            filter = rf_jailer
        })
        if tr.Hit then rf_jailer:SetPos(tr.HitPos) end
    end

    -- Spawn UK Jailer
    local uk_jailer = ents.Create("rhc_jailer_uk")
    if IsValid(uk_jailer) then
        uk_jailer:SetPos(Vector(-12438.240234, -9908.939453, 181.868973))
        uk_jailer:SetAngles(Angle(0, 180, 0))
        uk_jailer:Spawn()

        local tr = util.TraceLine({
            start = uk_jailer:GetPos() + Vector(0,0,10),
            endpos = uk_jailer:GetPos() - Vector(0,0,100),
            filter = uk_jailer
        })
        if tr.Hit then uk_jailer:SetPos(tr.HitPos) end
    end
end

hook.Add("InitPostEntity", "MRP_SpawnHandcuffsJailers", function()
    timer.Simple(5, SpawnJailers) -- Wait a bit to ensure map is fully loaded
end)

-- Make it easy to respawn via command if accidentally deleted
concommand.Add("mrp_respawn_jailers", function(ply)
    if IsValid(ply) and not ply:IsSuperAdmin() then return end
    SpawnJailers()
    if IsValid(ply) then ply:ChatPrint("NPC-тюремщики возрождены.") end
end)
