# shellcheck shell=dash disable=2269
# x agent job init "Implement user authentication"     # create job id
# x agent job iter --max-iterations 100 --inrow 10

xrc:mod:lib agent       job/util job/ls job/status job/prompt job/iter job/run job/stop job/retry job/rm


# x agent job bootstrap -- guiding users creating a job.

# x agent job init      -- create       -- no adjust
# x agent job iter      --addition "..."
# x agent job status    # running , stopped-to-be-continued, stopped-considered-done

# using ajob to offload missions.
# using

# File Directory structure.


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

    local op="$1"
    case "$op" in
        ls|status|run|stop|retry|rm)
                    shift; ___x_cmd_agent_job_"$op" "$@"        ;;
        -h|--help)  ___x_cmd help -m agent job; return 0        ;;
        *)          N=agent M="Unknown operation" log:ret:64    ;;
    esac
}

___X_CMD_AGENT_JOB_RECENT=""
___X_CMD_AGENT_JOB_DIR="$___X_CMD_ROOT_DATA/agent/job"

# Writes user's description to DESC.md, then calls AI to generate/update PLAN.md and AGENTS.md.
# Run a complete job: initialize then iterate until completion.
# When --retry is set, the job directory is assumed to exist and only the iteration loop runs.
___x_cmd_agent_job_exec(){
    [ $# -gt 0 ]    ||      set -- --help

    local mode="auto"
    local jobdir=""
    local jobid=""
    local harness=""
    local debug=""
    local max_iterations=100
    local inrow=2
    local continuous=""
    local retry=""
    local reinit=""
    while [ $# -gt 0 ]; do
        case "$1" in
            -h|--help)              ___x_cmd help -m agent job init; return 0 ;;
            --auto)                 mode=auto ;     shift ;;
            -b|--batch)             mode="batch" ;  shift ;;
            --job-dir)              jobdir="$2" ;   arg:2:shift ;;
            --job-id)               jobid="$2" ;    arg:2:shift ;;
            --harness)              harness="$2" ;  arg:2:shift ;;
            --debug)                debug=1 ;       shift ;;
            --max-iterations)       max_iterations="$2" ;       arg:2:int; arg:2:shift ;;
            --inrow)                inrow="$2" ;                arg:2:int; arg:2:shift ;;
            --continuous)           continuous=1;               shift ;;
            --retry)                retry=1;                    shift ;;
            --reinit)               reinit=1;                   shift ;;
            --)                     shift ; break ;;
            *)                      break ;;
        esac
    done

    local desc="$*"
    if [ -z "$retry" ]; then
        [ -n "$desc" ] || N=agent M="Please specify the job description" log:ret:64
    fi

    if [ -z "$jobid" ] && [ -z "$jobdir" ] && [ -n "$___X_CMD_AGENT_JOB_RECENT" ]; then
        jobdir="$___X_CMD_AGENT_JOB_RECENT"
    else
        [ -n "$jobid" ] || jobid="$(___x_cmd date vlid)"
        if [ -z "$jobdir" ]; then
            jobdir="$___X_CMD_AGENT_JOB_DIR/$jobid"
        else
            jobdir="$jobdir/$jobid" # Remove trailing slash if any
        fi

        ___X_CMD_AGENT_JOB_RECENT="$jobdir"
    fi

    local x_=""
    if [ -z "$harness" ]; then
        x_=""; ___x_cmd_agent_harness_
        harness="$x_"
    fi

    if [ -n "$retry" ]; then
        # Retry mode: reuse existing directory, optionally reinit plan, then iterate.
        if [ -n "$reinit" ]; then
            ___x_cmd_agent_job___reinit_plan "$jobdir" "$harness" "$debug" || return $?
        fi
        ___x_cmd_agent_job___iter "$jobdir"
        return $?
    fi

    ___x_cmd_agent_job___init "$jobdir" || return $?
    ___x_cmd_agent_job___iter "$jobdir"
}

# Initialize or re-initialize a job.
# Optional second argument: if non-empty, do not append a new description entry to DESC.md.
___x_cmd_agent_job___init(){
    local jobdir="$1"
    local no_desc_append="${2:-}"
    local is_init=0
    local vlid; vlid="$(___x_cmd date vlid)"
    if [ -d "$jobdir" ]; then
        # Re-init existing job: append to DESC.md unless suppressed
        if [ -z "$no_desc_append" ]; then
            printf "Timestamp: %s\nAdjust Desc: %s\n---\n" "$vlid" "$desc" >> "$jobdir/DESC.md"
        fi
    else
        # Init new job
        is_init=1
        ___x_cmd mkdirp "$jobdir"
        printf "Timestamp: %s\nPwd: %s\nDesc: %s\n---\n" "$vlid" "$PWD" "$desc" > "$jobdir/DESC.md"
    fi

    local descfile="$jobdir/DESC.md"
    local planfile="$jobdir/PLAN.md"
    local agentfile="$jobdir/AGENTS.md"

    # Call AI to generate/update PLAN.md and AGENTS.md
    local content;
    descfile="$descfile" planfile="$planfile" agentfile="$agentfile" jobdir="$jobdir" \
    content="$( ___x_cmd_agent_job___get_prompt init )"

    [ -n "$content" ] || {
        agent:error "Failed to load init prompt template"
        return 1
    }

    local debug_opt=""
    [ -z "$debug" ] || debug_opt="--debug"
    ___x_cmd agent request --harness "$harness" $debug_opt -f "$descfile" -f "$planfile" -f "$agentfile" "$content" || return $?

    [ -r "$planfile" ] || {
        agent:error "Failed to read PLAN.md after init. The AI may not have created the task plan properly"
        return 1
    }

    # Remove old DONE.md since the task plan has been adjusted
    if [ -f "$jobdir/DONE.md" ]; then
        ___x_cmd rmrf "$jobdir/DONE.md"
        agent:info "Removed old DONE.md - Task plan changed, previous completion status invalidated"
    fi

    if [ "$is_init" = 1 ]; then
        agent:info "Job created at $jobdir"
    else
        agent:info "Job re-initialized at $jobdir"
    fi
    agent:info "PLAN.md and AGENTS.md updated"
}

# Regenerate PLAN.md for an existing job while preserving AGENTS.md.
___x_cmd_agent_job___reinit_plan(){
    local jobdir="$1"
    local harness="${2:-}"
    local debug="${3:-}"

    [ -d "$jobdir" ] || {
        N=agent M="Job directory not found: $jobdir" log:ret:1
        return 1
    }

    local agentfile="$jobdir/AGENTS.md"
    local planfile="$jobdir/PLAN.md"
    local descfile="$jobdir/DESC.md"

    [ -f "$agentfile" ] || {
        N=agent M="AGENTS.md not found in $jobdir" log:ret:1
        return 1
    }

    local backup_agent=""
    backup_agent="$jobdir/.AGENTS.md.retry.bak"
    ___x_cmd_cmds cp "$agentfile" "$backup_agent" || return $?

    local content
    descfile="$descfile" planfile="$planfile" agentfile="$agentfile" jobdir="$jobdir" \
    content="$( ___x_cmd_agent_job___get_prompt init )"

    [ -n "$content" ] || {
        agent:error "Failed to load init prompt template"
        ___x_cmd rmrf "$backup_agent"
        return 1
    }

    local debug_opt=""
    [ -z "$debug" ] || debug_opt="--debug"
    if ! ___x_cmd agent request --harness "$harness" $debug_opt -f "$descfile" -f "$planfile" -f "$agentfile" "$content"; then
        ___x_cmd rmrf "$backup_agent"
        return $?
    fi

    # Preserve the original AGENTS.md as required by retry semantics.
    ___x_cmd_cmds mv "$backup_agent" "$agentfile"

    [ -r "$planfile" ] || {
        agent:error "Failed to read PLAN.md after re-init. The AI may not have created the task plan properly"
        return 1
    }

    # Remove stale completion artifacts
    for f in DONE.md SUMMARY.md ERROR.md; do
        [ ! -f "$jobdir/$f" ] || ___x_cmd rmrf "$jobdir/$f"
    done

    agent:info "PLAN.md regenerated at $jobdir (AGENTS.md preserved)"
}

