# shellcheck shell=sh        disable=SC2039,SC1090,SC3043,SC2263
# x-cmd cwe lib/la/fmt — output formatters for `x cwe ls` rows.
#
# All formatters take tab-separated rows on stdin and emit a different
# representation on stdout.

# Render one row as a small fixed-width table (used in fzf).
# Layout: "CWE-79  Base  Stable  Cross-site Scripting — The software..."
___x_cmd_cwe_la_fmt_row(){
    awk -F '\t' '
        NR == 1 { next }
        {
            id    = $1
            name  = $2
            abs   = $3
            stat  = $4
            desc  = $5
            printf "%-12s %-9s %-11s %-50s  %s\n", id, abs, stat, substr(name, 1, 50), desc
        }
    '
}

# Pretty fixed-width table with a header row.
___x_cmd_cwe_la_fmt_table(){
    printf "%-12s %-9s %-11s %-50s  %s\n" "CWE-ID" "ABSTRACTION" "STATUS" "NAME" "DESC"
    ___x_cmd_cwe_la_fmt_row
}

# Pretty multi-line blocks (for `x cwe ls --yml`).
___x_cmd_cwe_la_fmt_yml(){
    awk -F '\t' '
        NR == 1 { next }
        {
            printf "id:           %s\nname:         %s\nabstraction:  %s\nstatus:       %s\n",
                   $1, $2, $3, $4
            if ($5 != "") printf "desc:         %s\n", $5
            printf "\n"
        }
    '
}

___x_cmd_cwe_la_fmt_json(){
    awk -F '\t' '
        NR == 1 { next }
        function esc(s) {
            gsub(/\\/, "\\\\", s)
            gsub(/"/,  "\\\"", s)
            return s
        }
        {
            printf "{\"id\":\"%s\",\"name\":\"%s\",\"abstraction\":\"%s\",\"status\":\"%s\",\"desc\":\"%s\"}\n",
                   $1, esc($2), $3, $4, esc($5)
        }
    '
}

___x_cmd_cwe_la_fmt_csv(){
    awk -F '\t' '
        NR == 1 { next }
        { gsub(/"/, "\"\"", $2); gsub(/"/, "\"\"", $5); printf "%s,%s,%s,%s,\"%s\"\n", $1, $2, $3, $4, $5 }
    '
}