# shellcheck shell=dash

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

    local yml_file="" tsv_file="" feedback=""
    local TAB="$___X_CMD_UNSEENCHAR_HT"

    while [ $# -gt 0 ]; do
        case "$1" in
            -h|--help)  ___x_cmd help -m score iter "$@"; return 0 ;;
            -f)         yml_file="$2" ;  arg:2:shift ;;
            --)         shift ; break ;;
            *)          [ -z "$tsv_file" ] && tsv_file="$1" || feedback="$feedback $1" ; shift ;;
        esac
    done

    [ -n "$yml_file" ] || { N=score M="Usage: x score iter -f <score.yml> <score.tsv> <feedback>" log:ret:64; }
    [ -f "$yml_file" ] || { N=score M="File not found: $yml_file" log:ret:64; }
    [ -n "$tsv_file" ] || { N=score M="Usage: x score iter -f <score.yml> <score.tsv> <feedback>" log:ret:64; }
    [ -f "$tsv_file" ] || { N=score M="File not found: $tsv_file" log:ret:64; }
    [ -n "$feedback" ] || { N=score M="No feedback provided" log:ret:64; }

    # Locate skill0/score/ for SKILL.md
    local skill_dir=""
    ___x_cmd_score_skill_dir_ || { N=score M="Unable to locate skill0/score/" log:ret:64; }
    skill_dir="$x_"

    # Generate timestamp for temp file
    x_=""; ___x_cmd epoch get_
    local tmpfile="$___X_CMD_ROOT_TMP/score/iter/${x_}-$$.tsv"

    local system_prompt="\
You are a scoring assistant using the skill0/score framework.

## Scoring standard

$(___x_cmd_cmds cat "$yml_file")

## Current scores

$(___x_cmd_cmds cat "$tsv_file")

## User feedback

$feedback

## Task

1. Read SKILL.md for the full scoring framework: $skill_dir/SKILL.md
2. Review the current scores and evidence in light of the user feedback.
3. Update scores and evidence as needed.
4. Write the updated TSV to: $tmpfile

The TSV must have the EXACT SAME columns as the current scores file above.
Leave total and rank columns BLANK — they will be computed by compute.py.
Every score cell MUST have a corresponding evidence cell.

## Output path

- Output file: $tmpfile
"

    ___x_cmd agent request "$system_prompt" || return $?

    [ -s "$tmpfile" ] || { N=score M="AI returned empty result" log:ret:64; }

    # Backup original and replace
    cp "$tsv_file" "${tsv_file}.bak" || true
    cp "$tmpfile" "$tsv_file" || { N=score M="Failed to write $tsv_file" log:ret:64; }

    printf "Updated: %s\n" "$tsv_file"
    printf "Backup:  %s.bak\n" "$tsv_file"
    printf "Feedback: %s\n" "$feedback"
}
