
#include "cas_inc_rndloc"

void main()
{
    int nMsg = GetUserDefinedEventNumber();
    if (nMsg != 1001) return; // Only respond to fire event

    object oSelf = OBJECT_SELF;
    object oPC = GetFirstPC(); // Debug messages will be sent to first player
    string sCannonTag = GetTag(oSelf);

    SendMessageToPC(oPC, "DEBUG: cas_firecannons activated on object: " + sCannonTag);
    FloatingTextStringOnCreature("Firing script activated.", oSelf, FALSE);

    // Extract cannon number from tag (assumes "CAS_CANNONVFX#" format)
    if (GetStringLength(sCannonTag) < 14)
    {
        SendMessageToPC(oPC, "ERROR: Invalid cannon tag format. Expected CAS_CANNONVFX#.");
        FloatingTextStringOnCreature("ERROR: Invalid tag format.", oSelf, FALSE);
        return;
    }

    string sIndex = GetSubString(sCannonTag, 13); // Get number from the tag
    if (sIndex == "")
    {
        SendMessageToPC(oPC, "ERROR: Could not extract index from cannon tag: " + sCannonTag);
        FloatingTextStringOnCreature("ERROR: Tag missing index.", oSelf, FALSE);
        return;
    }

    string sTargetTag = "CAS_CANNONTARGET" + sIndex;
    SendMessageToPC(oPC, "DEBUG: Looking for target waypoint: " + sTargetTag);

    object oTarget = GetWaypointByTag(sTargetTag);
    if (!GetIsObjectValid(oTarget))
    {
        SendMessageToPC(oPC, "ERROR: Target waypoint not found: " + sTargetTag);
        FloatingTextStringOnCreature("ERROR: No target found!", oSelf, FALSE);
        return;
    }

    // Get source and randomized target location
    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;

    // Fire sequence
    SendMessageToPC(oPC, "DEBUG: Target location set. Distance = " + FloatToString(fDistance));
    SetFacingPoint(vTarget);

    ActionCastFakeSpellAtLocation(SPELL_FIREBALL, lTarget, PROJECTILE_PATH_TYPE_BALLISTIC);
    SendMessageToPC(oPC, "DEBUG: Projectile launched to " + sTargetTag);
    FloatingTextStringOnCreature("Cannon fired!", oSelf, FALSE);

    // 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 fires
    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)))
        ));
    }

    // Final boom
    PlaySound("as_pl_cannon");
}

