; Initialize variables if they don't exist
#if {%defined(ClientVersion)=0} {#var ClientVersion 0}
#if {%defined(AutomaticUpdate)=0} {#var AutomaticUpdate "disabled"}
#var SoundStatus {}
#var SoundStatusPrev {}
#var SyncUpdatePending 0
#file 4 sound_status.txt;
#write 4 { };
#close 4;
#file 4 sound_error.txt;
#write 4 { };
#close 4;
; Version Checking Triggers

; Captures lines like: "$soundpack vip last version: 13"
#trigger {$soundpack &SyncType last version: &SyncVer} {
  #gagline all;
  
  ; Only check vip version
  #if {@SyncType = "vip"} {
    #say {Updator: Checking @SyncType version. Local: @ClientVersion, Remote: @SyncVer};

    ; Check if update needed
    #if {@ClientVersion < @SyncVer} {
      #say {Updator: Update available for @SyncType.};
#if {@AutomaticUpdate="enabled"} {PerformUpdate}
    } {
      #say {Updator: @SyncType is up to date.}
    }
  }
}

; Update Automation

#alias PerformUpdate {
  #if {@SyncUpdatePending = 0} {
    #var SyncUpdatePending 1;
    ; Force refresh
    #var SoundStatusPrev {};
    
    ; Ensure monitor is running
    StartSyncMonitor;
    
    #say {Updator: Initiating script update sequence...};
    
    ; Step 1: Write command to sound_error.txt
    #DelFile {sound_error.txt};
    #file 4 sound_error.txt;
    #write 4 {update_scripts};
    #close 4;
    
    ; Step 2: Trigger the external updater
    LaunchSoundSync;
    
    #say {Updator: Update request sent to background process.};
    
    ; Reset pending flag after a delay
    #alarm 30 {#var SyncUpdatePending 0}
  } {
    #say {Updator: Update already in progress.}
  }
}

#alias FetchSound {
  #var SoundFile %0;
  ; Force refresh so we see the status even if unchanged
  #var SoundStatusPrev {};
  
  ; Ensure monitor is running
  StartSyncMonitor;
  
  #say {Updator: Requesting download for: @SoundFile};
  
  #DelFile {sound_error.txt};
  #file 4 sound_error.txt;
  #write 4 {%RTrim(@SoundFile).wav};
  #close 4;
  
  LaunchSoundSync
}

#alias LaunchSoundSync {
  #config editor {%homefolder\SoundSync.exe};
  #edit sound_error.txt;
  #config editor notepad.exe
}

; Sync Monitor Loop

#alias StartSyncMonitor {
  #var SoundStatusPrev {};
  
  ; Clear existing status file to prevent catching stale "Finished" signals
  #DelFile {sound_status.txt};
#file 10 sound_status.txt;
#write 10 { } 1;
#close 10;
  #alarm SyncMonitor -0.1 {
    CheckSyncStatus
  }
}

#alias StopSyncMonitor {
  #unalarm SyncMonitor;
}

#alias CheckSyncStatus {
  ; Read status file using handle 5 (Sequential)
  #file 5 sound_status.txt;
#read 5 CurrentStatus;
  #close 5;
  
  ; Guard against empty reads or EOF
  #if {@CurrentStatus = "[EOF]" OR @CurrentStatus = ""} {
     ; parsing failed or empty, skip this cycle
  } {
      ; Process only if status changed
      #if {@CurrentStatus <> @SoundStatusPrev} {
        ; Update prev status IMMEDIATELY to prevent looping if subsequent commands error out
        #var SoundStatusPrev @CurrentStatus;
        
        #var StatusCode {%word(@CurrentStatus,"|",1)};
        #var StatusMsg {%word(@CurrentStatus,"|",2)};
        
        ; Detailed Notification
        #if {%pos("Downloading", "@StatusCode") > 0} {
          #say {Updator: Downloading - @StatusMsg}
        };
        #if {%pos("Downloaded", "@StatusCode") > 0} {
          #say {Updator: Completed - @StatusMsg}
        };
        #if {%pos("Extracting", "@StatusCode") > 0} {
          #say {Updator: Extracting - @StatusMsg}
        };
        #if {%pos("Failed", "@StatusCode") > 0 OR %pos("404", "@StatusCode") > 0 OR %pos("Timeout", "@StatusCode") > 0} {
          #say {Updator: Error - @StatusCode: @StatusMsg}
        };
        #if {%pos("Finished", "@StatusCode") > 0} {
          #say {Updator: All downloads finished.};
          StopSyncMonitor
        };
        
        ; Handle specific states
        #if {%pos("Downloaded", "@StatusCode") > 0} {
          HandleDownloadSuccess @StatusMsg
        };
        
        #if {%pos("Failed", "@StatusCode") > 0 OR %pos("404", "@StatusCode") > 0 OR %pos("Timeout", "@StatusCode") > 0} {
          #play {@sppath/general/misc/boop.wav} @vol
        };
      }
  }
}

#alias HandleDownloadSuccess {
  #var DownloadedFile %0;
  
  ; Use %pos for maximum robustness. It ignores spaces and underscores.
  ; Checking for "Scripts" anywhere in the name.
  #if {%pos("Scripts", "@DownloadedFile") > 0} {
    #say {Updator: Scripts successfully updated! Reloading...};
    #play {@sppath/general/misc/spannouncement.wav} @vol;
StopSyncMonitor;
    #var SyncUpdatePending 0;
    spreload
  } {
    ; It's a sound file
    #say {Updator: NEW SOUND: @DownloadedFile};
echo @faildsound;
  }
}