
# scan: greedy scan for the most critical violation(s)
# output a tsv. stops after finding 1-5 top issues.

___x_cmd_rule_scan(){
    [ $# -gt 0 ]    ||  set -- --help

    local ruleset_dir=""
    local output_file=""
    local x_=""

    while [ $# -gt 0 ]; do
        case "$1" in
            -h|--help)  ___x_cmd help -m rule scan "$@" ;   return 0 ;;
            -r)         ruleset_dir="$2" ;  ___x_cmd_rule_ruleset_check_ "$ruleset_dir" || return $? ; arg:2:shift ;;
            -o)         output_file="$2" ;                  arg:2:shift ;;
            --)         shift ;     break ;;
            *)          break ;;
        esac
    done

    local IFS=' '
    local target_root="$1"

    case "$target_root" in
        :*)
            [ -n "$ruleset_dir" ] || {
                x_=""
                ___x_cmd_rule_preset_resolve_ "$target_root" || N=rule M="Preset '$target_root' not found" log:ret:64
                ruleset_dir="$x_"
            }
            target_root=""
            ;;
    esac

    [ -n "$ruleset_dir" ] || {
        x_=""
        ___x_cmd_rule_which_ || N=rule M="Fail to locate any ruleset. You can use -r to specify" log:ret:64
        ruleset_dir="$x_"
    }

    rule:info "Scan | ruleset:$ruleset_dir | target:$target_root"

    x_=""; ___x_cmd epoch get_
    local tmpfile="$___X_CMD_ROOT_TMP/rule/scan/${x_}-$$.tsv"
    local TAB="$___X_CMD_UNSEENCHAR_HT"

    local system_prompt="$___X_CMD_RULE_PROMPT_RULE_FMT
You are a quality checker performing a quick scan.

## Task

1. Read all rule files under: $ruleset_dir
   Each .yml file contains rules in the format shown above.
2. Read all files under: $target_root
3. Find the 1-5 most critical violations only.

## Strategy

- Do NOT try to be exhaustive. Focus on the most obvious, most severe violations.
- Trust your first instinct — if something looks wrong, report it immediately.
- Stop after finding 1-5 issues. Speed matters more than completeness.
- If nothing obviously wrong, output just the header row.

## Output

Write the complete TSV result to: $tmpfile

The TSV format is:

# The following are examples for illustration only
root${TAB}target${TAB}ruleid${TAB}score${TAB}hint
${target_root}${TAB}src/hello-world.sh${TAB}P06-var-010${TAB}10${TAB}变量命名不规范

Where:
- root: the root directory the target belongs to (use the value from Target path above)
- target: relative path to the source file under the root
- score: integer 0-80 (how severe the violation is)
- hint: brief explanation of the violation

## Paths

- Rules: $ruleset_dir
- Target root: $target_root
- Output file: $tmpfile
"

    ___x_cmd agent request --no-thinking "$system_prompt" || return $?

    [ -s "$tmpfile" ] || return 0

    rule:info "Scan completed | output:$tmpfile"

    if [ -n "$output_file" ]; then
        ___x_cmd_cmds cp "$tmpfile" "$output_file"
    else
        ___x_cmd_cmds cat "$tmpfile"
    fi
}
