local m=120254022
local cm=_G["c"..m]
cm.name="名流释放"
function cm.initial_effect(c)
	--Activate
	local e1=Effect.CreateEffect(c)
	e1:SetCategory(CATEGORY_TOHAND)
	e1:SetType(EFFECT_TYPE_ACTIVATE)
	e1:SetCode(EVENT_ATTACK_ANNOUNCE)
	e1:SetCondition(cm.condition)
	e1:SetCost(cm.cost)
	e1:SetTarget(cm.target)
	e1:SetOperation(cm.activate)
	c:RegisterEffect(e1)
end
--Activate
function cm.confilter(c)
	return c:IsFaceup() and c:IsAttribute(ATTRIBUTE_LIGHT) and c:IsRace(RACE_SPELLCASTER)
end
function cm.costfilter1(c)
	return c:IsFaceup() and c:IsType(TYPE_EQUIP) and c:IsAbleToDeckOrExtraAsCost()
end
function cm.costfilter2(c)
	return c:IsAttribute(ATTRIBUTE_LIGHT) and c:IsRace(RACE_SPELLCASTER) and c:IsAbleToDeckOrExtraAsCost()
end
function cm.filter(c)
	return c:IsAttackPos() and c:IsAbleToHand()
end
function cm.costcheck(g)
	return RD.GroupAllCount(g,Card.IsLocation,1,LOCATION_ONFIELD)
		or RD.GroupAllCount(g,Card.IsLocation,4,LOCATION_GRAVE)
end
function cm.condition(e,tp,eg,ep,ev,re,r,rp)
	return Duel.GetAttacker():IsControler(1-tp)
		and Duel.IsExistingMatchingCard(cm.confilter,tp,LOCATION_MZONE,0,1,nil)
end
function cm.cost(e,tp,eg,ep,ev,re,r,rp,chk)
	local g1=Duel.GetMatchingGroup(cm.costfilter1,tp,LOCATION_ONFIELD,0,nil)
	local g2=Duel.GetMatchingGroup(cm.costfilter2,tp,LOCATION_GRAVE,0,nil)
	if chk==0 then return g1:GetCount()>0 or g2:GetCount()>3 end
	local sg
	Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TODECK)
	if g1:GetCount()<1 then
		sg=g2:Select(tp,4,4,nil)
	elseif g2:GetCount()<4 then
		sg=g1:Select(tp,1,1,nil)
	else
		g1:Merge(g2)
		sg=g1:SelectSubGroup(tp,cm.costcheck,false,1,4)
	end
	Duel.SendtoDeck(sg,nil,SEQ_DECKSHUFFLE,REASON_COST)
end
function cm.target(e,tp,eg,ep,ev,re,r,rp,chk)
	if chk==0 then return Duel.IsExistingMatchingCard(cm.filter,tp,0,LOCATION_MZONE,1,nil) end
	local g=Duel.GetMatchingGroup(cm.filter,tp,0,LOCATION_MZONE,nil)
	Duel.SetOperationInfo(0,CATEGORY_TOHAND,g,1,0,0)
end
function cm.activate(e,tp,eg,ep,ev,re,r,rp)
	RD.SelectAndDoAction(HINTMSG_RTOHAND,cm.filter,tp,0,LOCATION_MZONE,1,3,nil,function(g)
		RD.SendToOpponentHand(g)
	end)
end