-- parasite_rat.lua (5 stages)
-- S2: more teeth, breeding → blood material darkens, gnaw damage
-- S3: crowded, fight for space → blood particle trail, internal fighting damage
-- S4: tunnels of gnawed flesh → max HP reduced (tissue loss), blood trail
-- S5: rat king → spawn boss-sized rat, all rats charmed
dofile_once("mods/lewd_noita/files/status_effects/parasite_utils.lua")
dofile_once("mods/lewd_noita/files/status_effects/parasite_compulsion.lua")
dofile_once("mods/lewd_noita/files/text/ln_text.lua")


local MAX_STAGE = 5
local SPAWN_INTERVAL_MIN = 15 * 60
local SPAWN_INTERVAL_MAX = 50 * 60

local entity = GetUpdatedEntityID()
local vsc = get_parasite_timer_vsc(entity)
if vsc == nil then return end

local player_id = EntityGetParent(entity)
if player_id == nil or player_id == 0 then return end
local UI_MSG = "mods/lewd_noita/files/sex_logic/ui_msg.png"

local dmg_comp_h = EntityGetFirstComponent(player_id, "DamageModelComponent")
if dmg_comp_h ~= nil then
	local hp = tonumber(ComponentGetValue2(dmg_comp_h, "hp")) or 0
	local max_hp = tonumber(ComponentGetValue2(dmg_comp_h, "max_hp")) or 0
	local prev_hp = tonumber(GlobalsGetValue("LN_PREV_HP_RAT", "-1"))
	GlobalsSetValue("LN_PREV_HP_RAT", tostring(hp))
	if prev_hp >= 0 and max_hp > 0 and hp >= max_hp and prev_hp < max_hp then
		-- Undo blood change on cure
		if dmg_comp_h then ComponentSetValue2(dmg_comp_h, "blood_material", "blood") end
		remove_parasite_emitter(player_id, "ln_em_rat")
		remove_parasite_overlay(player_id, "rat")
		force_release_compulsion(player_id, "parasite_rat")
		EntityKill(entity)
		ln_print_cure("parasite_rat", UI_MSG)
		return
	end
end

local stage, did_advance = check_parasite_stage_change(entity, MAX_STAGE, "LN_STAGE_ANN_RAT")
update_parasite_overlay(player_id, "rat", stage)

if did_advance then
	ln_print_stage("parasite_rat", stage, UI_MSG)
end

local frame = GameGetFrameNum()
local px, py = EntityGetTransform(player_id)
SetRandomSeed(frame, entity)

-- S2+: blood darkens (gnawed innards), gnaw damage
	-- Scratch-burst particles (claws raking inside)
	if frame % 30 == 0 then
		for i = 1, stage do
			GameCreateParticle("blood_cold", px + Random(-2,2), py + Random(-4,2), 2, Random(-8,8), Random(-12,-4), false)
		end
	end
if stage >= 2 and dmg_comp_h then
	ComponentSetValue2(dmg_comp_h, "blood_material", "blood_cold")
	if Random(1, stage >= 4 and 6 or 12) == 1 then
		local max_hp = tonumber(ComponentGetValue2(dmg_comp_h, "max_hp")) or 4
		EntityInflictDamage(player_id, max_hp * 0.015, "DAMAGE_MELEE", "rat gnawing", "NORMAL", 0, 0)
	end
end

-- S3+: crowded nest - blood leaks from fighting, blood particle trail
if stage >= 3 then
	-- Internal fighting causes extra damage bursts
	if Random(1, 20) == 1 then
		GameCreateParticle("blood_cold", px, py, 5, Random(-5,5), Random(-5,5), false)
	end
end

-- S4+: warren tunnels reduce max HP (tissue destruction)
if stage >= 4 and frame % 300 == 0 and dmg_comp_h then
	local max_hp = tonumber(ComponentGetValue2(dmg_comp_h, "max_hp")) or 4
	local min_hp = max_hp * 0.5 -- floor at 50% of original max
	local original_max = tonumber(GlobalsGetValue("LN_RAT_ORIG_MAXHP", "0"))
	if original_max == 0 then
		GlobalsSetValue("LN_RAT_ORIG_MAXHP", tostring(max_hp))
		original_max = max_hp
	end
	if max_hp > original_max * 0.5 then
		ComponentSetValue2(dmg_comp_h, "max_hp", max_hp - original_max * 0.005)
	end
end

-- S5: rat king - charm all rats nearby, once spawn a skullrat as "rat king"
if stage >= 5 then
	if frame % 90 == 0 then
		for _, e in ipairs(EntityGetInRadiusWithTag(px, py, 120, "enemy") or {}) do
			local fname = EntityGetFilename(e) or ""
			if fname:find("rat") then
				GetGameEffectLoadTo(e, "CHARM", true)
			end
		end
	end
	-- Spawn the rat king once
	if not GameHasFlagRun("LN_RAT_KING_SPAWNED") then
		GameAddFlagRun("LN_RAT_KING_SPAWNED")
		local king = EntityLoad("data/entities/animals/skullrat.xml", px, py - 5)
		if king and king ~= 0 then
			GetGameEffectLoadTo(king, "CHARM", true)
		end
		ln_print_text_pair(LN_TEXT.parasite_rat.rat_king, UI_MSG)
	end
end


-- Particle emitter (stage 4+)
if stage >= 4 then
	attach_parasite_emitter(player_id, "ln_em_rat", "mods/lewd_noita/files/particles/emitter_silk.xml")
end

-- COMPULSION
try_compulsion(player_id, "parasite_rat", stage, {
	min_stage = 3,
	duration_min = 90, duration_max = 180,
	cooldown_min = 35 * 60, cooldown_max = 70 * 60,
})

-- Inner monologue
local msg_next = tonumber(GlobalsGetValue("LN_MSG_RAT", "0"))
if msg_next == 0 then
	SetRandomSeed(frame, entity + 111)
	GlobalsSetValue("LN_MSG_RAT", tostring(frame + Random(30 * 60, 150 * 60)))
elseif frame >= msg_next then
	SetRandomSeed(frame, entity + 111)
	ln_print_monologue("parasite_rat", UI_MSG)
	GlobalsSetValue("LN_MSG_RAT", tostring(frame + Random(30 * 60, 150 * 60)))
end

if EntityGetWithName("ln_sex_cooldown") ~= 0 then return end

local already_pregnant_this_source = false
for _, child in ipairs(EntityGetAllChildren(player_id) or {}) do
	if EntityGetName(child) == "ln_pregnancy" then
		local pvsc = EntityGetFirstComponent(child, "VariableStorageComponent")
		if pvsc ~= nil and ComponentGetValue2(pvsc, "value_string") == "data/entities/animals/rat.xml" then
			already_pregnant_this_source = true
			break
		end
	end
end
if already_pregnant_this_source then return end

local dmg_comp = EntityGetFirstComponent(player_id, "DamageModelComponent")
if dmg_comp ~= nil and ComponentGetValue2(dmg_comp, "is_on_fire") == true then return end

local last_spawn = tonumber(ComponentGetValue2(vsc, "value_string")) or 0
local next_interval = tonumber(ComponentGetValue2(vsc, "value_int")) or 0
local mult = get_spawn_interval_mult(stage)

if next_interval == 0 then
	SetRandomSeed(frame, entity)
	next_interval = math.floor(Random(SPAWN_INTERVAL_MIN, SPAWN_INTERVAL_MAX) * mult)
	ComponentSetValue2(vsc, "value_int", next_interval)
	ComponentSetValue2(vsc, "value_string", tostring(frame))
	return
end
if frame - last_spawn < next_interval then return end

SetRandomSeed(frame, entity)
local function create_pregnancy(file)
	local pregnancy = EntityCreateNew("ln_pregnancy")
	EntityAddComponent2(pregnancy, "InheritTransformComponent", {})
	EntityAddComponent2(pregnancy, "GameEffectComponent", { effect="CUSTOM", custom_effect_id="EFFECT_PREGNANCY" })
	EntityAddComponent2(pregnancy, "UIIconComponent", { icon_sprite_file="mods/lewd_noita/files/status_effects/pregnant.png", name="Pregnant", description=ln_spawn_pregnancy_desc("parasite_rat") })
	EntityAddComponent2(pregnancy, "VariableStorageComponent", { value_string=file, value_int=GameGetFrameNum() })
	EntityAddComponent2(pregnancy, "LuaComponent", { script_source_file="mods/lewd_noita/files/sex_logic/start_birth.lua", execute_every_n_frame=Random(60, 90) * 60, remove_after_executed=true })
	EntityAddChild(player_id, pregnancy)
end

create_pregnancy("data/entities/animals/rat.xml")
if stage >= 3 and Random(1, stage >= 5 and 1 or 3) == 1 then
	create_pregnancy("data/entities/animals/rat.xml")
	ln_print_spawn("parasite_rat", "twin", UI_MSG)
else
	ln_print_spawn("parasite_rat", "single", UI_MSG)
end

ComponentSetValue2(vsc, "value_string", tostring(frame))
ComponentSetValue2(vsc, "value_int", math.floor(Random(SPAWN_INTERVAL_MIN, SPAWN_INTERVAL_MAX) * mult))
