#!/usr/bin/env nu

# Development Server with Filtered Output
# Nushell version of dev-quiet.sh
# Starts development server while filtering out noisy Leptos reactive warnings

def main [] {
    print $"(ansi blue)🚀 Starting development server (filtered output)...(ansi reset)"

    # Build CSS first
    print $"(ansi blue)🎨 Building CSS...(ansi reset)"
    try {
        pnpm run build:all
    } catch {
        print $"(ansi red)❌ CSS build failed(ansi reset)"
        exit 1
    }

    # Clean up existing servers
    print $"(ansi blue)🔄 Cleaning up existing servers...(ansi reset)"
    cleanup_ports

    # Warning patterns to filter out (following project's anti-hardcoding principles)
    let warning_patterns = [
        "you access a reactive_graph",
        "outside a reactive tracking context",
        "Here's how to fix it:",
        "❌ NO",
        "✅ YES",
        "If this is inside a `view!` macro",
        "If it's in the body of a component",
        "If you're *trying* to access the value",
        "make sure you are passing a function",
        "try wrapping this access in a closure",
        "use \\.get_untracked\\(\\) or \\.with_untracked\\(\\)"
    ]

    print $"(ansi blue)📡 Starting Leptos server with filtered output...(ansi reset)"
    print $"(ansi yellow)💡 Filtering out reactive graph warnings for cleaner output(ansi reset)"

    # Start server with output filtering
    # Using Nushell's structured approach to handle output filtering
    try {
        bash -c "cargo leptos serve 2>&1"
        | lines
        | where {|line|
            not ($warning_patterns | any {|pattern| ($line | str contains $pattern)})
        }
        | each {|line| print $line}
    } catch {
        print $"(ansi red)❌ Failed to start development server(ansi reset)"
        exit 1
    }
}

# Helper function to cleanup ports
def cleanup_ports [] {
    # Kill processes on common development ports
    let ports = [3030, 3031]

    for port in $ports {
        try {
            let pids = (lsof -ti:$port | lines)
            if not ($pids | is-empty) {
                $pids | each {|pid|
                    kill -9 ($pid | into int)
                    print $"(ansi yellow)🔄 Killed process ($pid) on port ($port)(ansi reset)"
                }
            }
        } catch {
            # Ignore errors when no processes are found
        }
    }
}
