#include "cas_inc_rndloc"

void main()
{
    SendMessageToPC(GetFirstPC(), "DEBUG: cas_firecannons script STARTED");

    int nMsg = GetUserDefinedEventNumber();
    object oSelf = OBJECT_SELF;
    object oPC = GetFirstPC();

    if (nMsg == -1)
    {
        SendMessageToPC(oPC, "DEBUG: Script run via ExecuteScript()");
    }
    else if (nMsg == 1001)
    {
        SendMessageToPC(oPC, "DEBUG: Script triggered via SignalEvent (UserDefined: 1001)");
    }
    else
    {
        SendMessageToPC(oPC, "DEBUG: cas_firecannons exiting - unsupported event ID.");
        return;
    }

    ActionSpeakString("Firing sequence initiated!");

    // Get custom or fallback target
    string sTargetTag = GetLocalString(oSelf, "TARGET_TAG");
    if (sTargetTag == "")
    {
        SendMessageToPC(oPC, "DEBUG: No TARGET_TAG set, using nearest CAS_CANNONTARGET.");
        object oNearest = GetNearestObjectByTag("CAS_CANNONTARGET", oSelf);

        if (!GetIsObjectValid(oNearest))
        {
            ActionSpeakString("ERROR: No target!");
            SendMessageToPC(oPC, "ERROR: No valid CAS_CANNONTARGET found.");
            return;
        }

        sTargetTag = GetTag(oNearest);
    }

    object oTarget = GetWaypointByTag(sTargetTag);
    if (!GetIsObjectValid(oTarget))
    {
        ActionSpeakString("ERROR: Target missing!");
        SendMessageToPC(oPC, "ERROR: Target waypoint not found: " + sTargetTag);
        return;
    }

    // Fire setup
    location lSelf = GetLocation(oSelf);
    location lTarget = GetLocation(oTarget);
    vector vTarget = GetPositionFromLocation(lTarget);

    float fYOffset = RndFloat(20) * RndSign();
    float fZOffset = RndFloat(2);
    vTarget.y += fYOffset;
    vTarget.z += fZOffset;
    lTarget = Location(GetArea(oTarget), vTarget, GetFacing(oTarget));

    float fDistance = GetDistanceBetweenLocations(lTarget, lSelf);
    float fDelay = fDistance / 15.0;

    SendMessageToPC(oPC, "DEBUG: Target: " + sTargetTag + " | Distance: " + FloatToString(fDistance));
    SetFacingPoint(vTarget);
    ActionCastFakeSpellAtLocation(SPELL_FIREBALL, lTarget, PROJECTILE_PATH_TYPE_BALLISTIC);
    ActionSpeakString("Cannon fired!");

    // Explosion
    DelayCommand(fDelay, ApplyEffectAtLocation(
        DURATION_TYPE_INSTANT,
        EffectVisualEffect(VFX_FNF_FIREBALL),
        lTarget));

    // Debris
    DelayCommand(fDelay + 0.1, ApplyEffectToObject(
        DURATION_TYPE_TEMPORARY,
        EffectVisualEffect(VFX_DUR_PROT_GREATER_STONESKIN),
        DestroyObjectReturn(CreateObject(
            OBJECT_TYPE_PLACEABLE,
            "plc_stones",
            lTarget, TRUE),
        IntToFloat(d6(4)))
    ));

    // Splash effects
    int i, iCount = d3(3);
    for (i = 1; i <= iCount; i++)
    {
        location lSplash = RndLoc(lTarget, 6, 2, BASE_SHAPE_CIRCLE);
        DelayCommand(fDelay + 0.2, ApplyEffectToObject(
            DURATION_TYPE_TEMPORARY,
            EffectVisualEffect(VFX_FNF_FIREBALL),
            DestroyObjectReturn(CreateObject(
                OBJECT_TYPE_PLACEABLE,
                "plc_flamesmall",
                lSplash, TRUE),
            IntToFloat(d6(3)))
        ));
    }

    PlaySound("as_pl_cannon");
}
