#!/usr/bin/env bash
# update_yaml_resumed.sh — multi-agent-mux-resume 의 부속 스크립트
# Resume 한 세션의 agent-sessions.yaml 엔트리를 status=running + resume 메타로 갱신.
# resume UUID 를 per-row own id (claude_session_id_own / agy_conversation_id_own)
# 에 박는다 — agent_identities 전역은 더 이상 primary 아님 (cache 로 강등, P0-C/단계 e).
#
# Usage: bash update_yaml_resumed.sh --session <name> --uuid <id> [--agent claude|agy|hermes|grok|opencode]
set -euo pipefail

source "$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)/lib.sh"

usage() {
  cat <<EOF
Usage: $0 --session <name> --uuid <id> [--agent claude|agy|hermes|grok|opencode] [--herdr-session <name>] [--cmd-full <cmd>]

--uuid may be empty for an Issue-3 Class A fresh-spawn resume (agy/hermes/
opencode 0-turn stopped session, no conversation id ever assigned) - pass
--cmd-full so the display command can be recorded without a uuid to embed.
EOF
}

SESSION_NAME=""
UUID=""
AGENT=""
WORKSPACE=""
ROLE=""
HERDR_SERVER_OPT=""
HERDR_WORKSPACE_OPT=""
CMD_FULL_OPT=""

while [ $# -gt 0 ]; do
  case "$1" in
    --session)   SESSION_NAME="$2"; shift 2 ;;
    --uuid)      UUID="$2";          shift 2 ;;
    --agent)     AGENT="$2";         shift 2 ;;
    --workspace) WORKSPACE="$2";     shift 2 ;;
    --role)      ROLE="$2";          shift 2 ;;
    --herdr-session|--herdr-server) HERDR_SERVER_OPT="$2"; shift 2 ;;
    --herdr-workspace) HERDR_WORKSPACE_OPT="$2"; shift 2 ;;
    --cmd-full)  CMD_FULL_OPT="$2";  shift 2 ;;
    -h|--help) usage; exit 0 ;;
    *) echo "ERROR: unknown arg: $1" >&2; exit 2 ;;
  esac
done

[ -n "$SESSION_NAME" ] || { echo "ERROR: --session required" >&2; exit 2; }
[ -f "$AGENT_SESSIONS_YAML" ] || { echo "ERROR: $AGENT_SESSIONS_YAML not found" >&2; exit 1; }

if [ -n "$HERDR_SERVER_OPT" ]; then
  export HERDR_SESSION_NAME="$HERDR_SERVER_OPT"
  export HERDR_SERVER_OPT_EXPLICIT="1"
else
  HERDR_SESSION_NAME="$(resolve_herdr_session "$SESSION_NAME" "${WORKSPACE:-}")"
  export HERDR_SESSION_NAME
  export HERDR_SERVER_OPT_EXPLICIT="0"
fi

if [ -n "$HERDR_WORKSPACE_OPT" ]; then
  MAM_WS_LABEL="$HERDR_WORKSPACE_OPT"
  export MAM_WS_LABEL_EXPLICIT="1"
else
  MAM_WS_LABEL="$(resolve_herdr_workspace "$SESSION_NAME" "${WORKSPACE:-}")"
  export MAM_WS_LABEL_EXPLICIT="0"
fi
export MAM_WS_LABEL

# --agent 미지정 시 레지스트리 기록으로 해석 (B-21).
# ① row['agent'] → ② 세션명 접미사 → ③ pane.cmd 순. 셋 다 실패하면
# 종전과 동일하게 exit 2 (헤더 :27-30 의 종료 코드 계약 유지).
if [ -z "$AGENT" ]; then
  AGENT="$(resolve_agent_type_from_registry "$SESSION_NAME")" || AGENT=""
  [ -n "$AGENT" ] || {
    echo "ERROR: cannot infer agent from '$SESSION_NAME'; pass --agent" >&2
    exit 2
  }
fi

if [ -z "$ROLE" ]; then
  case "$SESSION_NAME" in
    *-planner-*)  ROLE="planner" ;;
    *-reviewer-*) ROLE="reviewer" ;;
    *)            ROLE="creator" ;;
  esac
fi

NOW_ISO=$(date -u +'%Y-%m-%dT%H:%M:%SZ')
NOW_EPOCH=$(date +%s)

# 새 herdr pane pid / 자식 pid 를 bash 에서 캡처 (env 로 전달, P1-B)
PANE_PID=$(_herdr list-panes -t "$SESSION_NAME" -F '#{pane_pid}' 2>/dev/null | head -1 || true)
PANE_PID="${PANE_PID:-}"
CHILD_PID=0
if { [ "$AGENT" = "agy" ] || [ "$AGENT" = "hermes" ]; } && [ -n "$PANE_PID" ]; then
  CHILD_PID=$(pgrep -P "$PANE_PID" -x "$AGENT" 2>/dev/null | head -1 || true)
  CHILD_PID="${CHILD_PID:-0}"
fi

DELEGATE_JOB_ID=$(MAM_STATE_JSON="$(load_state_json)" SESSION_NAME="$SESSION_NAME" python3 -c "
import sys, os, json
name = os.environ['SESSION_NAME']
d = json.loads(os.environ.get('MAM_STATE_JSON', '{}'))
for s in d.get('herdr_sessions', []):
    if s.get('name') == name:
        print(s.get('delegate_job_id', '') or '')
        sys.exit(0)
")

atomic_dump_yaml "$AGENT_SESSIONS_YAML" \
  SESSION_NAME="$SESSION_NAME" UUID="$UUID" AGENT="$AGENT" NOW_ISO="$NOW_ISO" \
  NOW_EPOCH="$NOW_EPOCH" TARGET_WORKSPACE="${WORKSPACE:-$WORKSPACE_ROOT}" ROLE="$ROLE" \
  PANE_PID="$PANE_PID" CHILD_PID="$CHILD_PID" HERDR_SERVER_OPT_EXPLICIT="${HERDR_SERVER_OPT_EXPLICIT:-0}" \
  MAM_WS_LABEL="$MAM_WS_LABEL" MAM_WS_LABEL_EXPLICIT="${MAM_WS_LABEL_EXPLICIT:-0}" \
  CMD_FULL_OPT="$CMD_FULL_OPT" <<'PYEOF'
name = os.environ['SESSION_NAME']
uuid = os.environ['UUID']
agent = os.environ['AGENT']
now = os.environ['NOW_ISO']
epoch = int(os.environ.get('NOW_EPOCH', '0') or '0')
ws_root = os.environ.get('TARGET_WORKSPACE', '') or os.environ.get('WORKSPACE_ROOT', '')
role = os.environ.get('ROLE', 'creator')
pane_pid = os.environ.get('PANE_PID', '')

target = None
for s in d.get('herdr_sessions', []):
    if s.get('name') == name:
        target = s
        break

if target is None:
    pwd = os.path.abspath(ws_root)
    default_server = 'mam-' + os.path.basename(pwd).lower().replace('_', '-')
    server_name = os.environ.get('HERDR_SESSION_NAME', default_server)
    wsl = os.environ.get('MAM_WS_LABEL', '')
    target = {
        'name': name,
        'status': 'running',
        'role': role,
        'herdr_session_created_at': now,
        'herdr_session_epoch': epoch,
        'herdr_session': server_name,
        'herdr_server': server_name,
        'herdr_workspace': wsl,
        'delegate_job_id': None,
        'pane': {'index': 0, 'pid': int(pane_pid) if pane_pid.isdigit() else 0, 'cmd': agent, 'cwd': ws_root},
        'start_command': f'HERDR_SESSION_NAME={server_name} herdr agent attach {name}',
        'attach_command': f'HERDR_SESSION_NAME={server_name} herdr agent attach {name}',
        'kill_command': f'HERDR_SESSION_NAME={server_name} herdr kill-session -t {name}',
    }
    d.setdefault('herdr_sessions', []).append(target)
else:
    sn = os.environ.get('HERDR_SESSION_NAME')
    is_explicit = os.environ.get('HERDR_SERVER_OPT_EXPLICIT') == '1'
    if sn:
        if is_explicit or not target.get('herdr_session'):
            target['herdr_session'] = sn
            target['herdr_server'] = sn
            target['start_command'] = f'HERDR_SESSION_NAME={sn} herdr agent attach {name}'
            target['attach_command'] = f'HERDR_SESSION_NAME={sn} herdr agent attach {name}'
            target['kill_command'] = f'HERDR_SESSION_NAME={sn} herdr kill-session -t {name}'
    wsl = os.environ.get('MAM_WS_LABEL', '')
    ws_explicit = os.environ.get('MAM_WS_LABEL_EXPLICIT') == '1'
    if wsl and (ws_explicit or not target.get('herdr_workspace')):
        target['herdr_workspace'] = wsl

target['status'] = 'running'
if not uuid:
    # ISSUE-3 (challenge c4b0a075): a Class A fresh-spawn resume re-arms
    # discovery from scratch - the resumed agent has not spoken yet, so any
    # on-disk conversation older than THIS resume must not be auto-pinned to
    # it by reconcile.sh's mode="discover" mtime >= epoch check. Without this,
    # the row's watermark stays at the original create_session.sh timestamp,
    # letting reconcile.sh capture a stale/unrelated transcript before the
    # resumed agent's first real turn.
    target['herdr_session_epoch'] = epoch
    target['herdr_session_created_at'] = now
    target['session_id_source'] = 'pending-discovery'
    target['session_id_verified'] = False
target.pop('terminated_at', None)
target.pop('terminated_at_epoch', None)
target.pop('termination_mode', None)
target.pop('archived_at', None)
# stop 메타도 정리 — resume 하면 더 이상 stopped 상태가 아니므로 잔존 필드를 제거.
target.pop('stopped_at', None)
target.pop('stopped_at_epoch', None)
target.pop('stop_reason', None)
target.pop('resumable', None)
if uuid:
    target['last_visible_status'] = f'resumed conversation {uuid} at {now}'
else:
    # ISSUE-3 Class A fresh-spawn resume: no conversation id existed yet.
    target['last_visible_status'] = f'resumed (fresh spawn, no prior turn) at {now}'

target.setdefault('pane', {})
if pane_pid.isdigit():
    target['pane']['pid'] = int(pane_pid)

if agent == 'claude':
    target['pane']['cmd'] = 'claude'
    target['pane']['cmd_full'] = f'claude --dangerously-skip-permissions -r {uuid}'
    target['claude_session_id_own'] = uuid
elif agent == 'agy':
    target['pane']['cmd'] = 'agy'
    if uuid:
        target['pane']['cmd_full'] = f'agy --dangerously-skip-permissions --conversation {uuid}'
        target['agy_conversation_id_own'] = uuid
    else:
        target['pane']['cmd_full'] = os.environ.get('CMD_FULL_OPT', '') or 'agy --dangerously-skip-permissions'
    cp = os.environ.get('CHILD_PID', '0')
    if cp.isdigit() and int(cp) > 0:
        target['child_pid'] = int(cp)
elif agent == 'hermes':
    target['pane']['cmd'] = 'hermes'
    if uuid:
        target['pane']['cmd_full'] = f'hermes --resume {uuid}'
        target['hermes_conversation_id_own'] = uuid
    else:
        target['pane']['cmd_full'] = os.environ.get('CMD_FULL_OPT', '') or 'hermes --yolo --accept-hooks'
    cp = os.environ.get('CHILD_PID', '0')
    if cp.isdigit() and int(cp) > 0:
        target['child_pid'] = int(cp)
elif agent == 'grok':
    target['pane']['cmd'] = 'grok'
    target['pane']['cmd_full'] = f'grok --resume {uuid}'
    target['grok_session_id_own'] = uuid
    cp = os.environ.get('CHILD_PID', '0')
    if cp.isdigit() and int(cp) > 0:
        target['child_pid'] = int(cp)
elif agent == 'opencode':
    target['pane']['cmd'] = 'opencode'
    if uuid:
        target['pane']['cmd_full'] = f'opencode --session {uuid} --auto --agent build'
        target['opencode_session_id_own'] = uuid
    else:
        target['pane']['cmd_full'] = os.environ.get('CMD_FULL_OPT', '') or 'opencode --auto --agent build'
    cp = os.environ.get('CHILD_PID', '0')
    if cp.isdigit() and int(cp) > 0:
        target['child_pid'] = int(cp)

snap = d.setdefault('snapshot', {})
snap['taken_at'] = now
snap.pop('terminated_at', None)
snap.pop('terminated_at_epoch', None)

print(f"updated: {name} status=running (resume id -> per-row own id)", flush=True)
PYEOF

delegate_publish_event "$DELEGATE_JOB_ID" progress "resumed"
