#!/usr/bin/env nu

# Kill Process on Ports Script
# Nushell version of kill-3030.sh
# Kills processes running on ports 3030 and 3031

def main [] {
    print $"(ansi blue)🔪 Killing processes on development ports...(ansi reset)"

    kill_port_processes 3030
    kill_port_processes 3031

    print $"(ansi green)✅ Port cleanup completed(ansi reset)"
}

# Kill processes on a specific port
def kill_port_processes [port: int] {
    print $"(ansi yellow)🔍 Checking port ($port)...(ansi reset)"

    try {
        # Get PIDs of processes using the port
        let pids = (lsof -ti $":($port)" | lines | where {|line| not ($line | str trim | is-empty)})

        if ($pids | is-empty) {
            print $"(ansi blue)ℹ️  No processes found on port ($port)(ansi reset)"
        } else {
            print $"(ansi yellow)⚠️  Found ($pids | length) process(es) on port ($port): ($pids | str join ', ')(ansi reset)"

            for pid in $pids {
                try {
                    kill -9 ($pid | into int)
                    print $"(ansi green)✅ Killed process ($pid) on port ($port)(ansi reset)"
                } catch {
                    print $"(ansi red)❌ Failed to kill process ($pid) on port ($port)(ansi reset)"
                }
            }
        }
    } catch {
        print $"(ansi blue)ℹ️  No processes found on port ($port) (lsof failed)(ansi reset)"
    }
}
