#!/usr/bin/env nu
# Filter WASM/bindgen noise from browser log output
# Usage: <log-data> | nu filter-wasm-noise.nu
# Or: nu filter-wasm-noise.nu --input "..." --level errors

def main [
    --level: string = "all"  # all | errors | warnings
    --raw                    # Show raw filtered text, not structured
] {
    let noise_patterns = [
        "__wbindgen"
        "wasm-bindgen"
        "instantiateStreaming"
        "WebAssembly.instantiate"
        "wasm_bindgen"
        "pkg/website_bg"
        "pkg/website.js"
        "at wasm"
        "at Object.module"
        "wbg."
        "closure invoked recursively"
        "leptos_dom"
        "using `console_error_panic_hook`"
    ]

    let input_text = $in | default ""

    if ($input_text | is-empty) {
        print "No input provided. Pipe log data into this script."
        print "Example: 'log text here' | nu filter-wasm-noise.nu"
        return
    }

    let lines = $input_text | lines

    let filtered = $lines | where { |line|
        let is_noise = $noise_patterns | any { |pat| $line | str contains $pat }
        not $is_noise
    } | where { |line|
        match $level {
            "errors" => ($line | str contains -i "error"),
            "warnings" => (($line | str contains -i "error") or ($line | str contains -i "warn")),
            _ => true,
        }
    }

    let total = $lines | length
    let kept = $filtered | length
    let removed = $total - $kept

    if not $raw {
        print $"(ansi green)Filtered: kept ($kept)/($total) lines, removed ($removed) WASM noise lines(ansi reset)"
        print ""
    }

    $filtered | each { |line| print $line }
}
