#!/usr/bin/env bash
set -euo pipefail
#
# session-run.sh — Generate continuation context and launch target runtime.
#
# Usage:
#   session-run.sh [--project <path>] [--milestone <id>] [--print] [--yolo]
#
# Behavior:
# - Builds continuation prompt + next-task capsule.
# - Launches selected runtime (default: claude, override via MOSAIC_COORD_RUNTIME).
# - For codex, injects strict orchestration kickoff to reduce clarification loops.
# - --yolo launches the runtime in dangerous/skip-permissions mode.

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

PROJECT="."
MILESTONE=""
PRINT=false
YOLO=false

while [[ $# -gt 0 ]]; do
  case "$1" in
    --project)   PROJECT="$2"; shift 2 ;;
    --milestone) MILESTONE="$2"; shift 2 ;;
    --print)     PRINT=true; shift ;;
    --yolo)      YOLO=true; shift ;;
    -h|--help)
      cat <<'USAGE'
Usage: session-run.sh [--project <path>] [--milestone <id>] [--print] [--yolo]

Options:
  --project <path>   Project directory (default: CWD)
  --milestone <id>   Force specific milestone context
  --print            Print launch prompt only (no runtime launch)
  --yolo             Launch runtime in dangerous/skip-permissions mode
USAGE
      exit 0
      ;;
    *) echo "Unknown option: $1" >&2; exit 1 ;;
  esac
done

PROJECT="${PROJECT/#\~/$HOME}"
PROJECT="$(cd "$PROJECT" && pwd)"

_require_jq
require_mission "$PROJECT"

runtime="$(coord_runtime)"
launch_cmd="$(coord_launch_command)"

continue_cmd=(bash "$SCRIPT_DIR/continue-prompt.sh" --project "$PROJECT")
if [[ -n "$MILESTONE" ]]; then
  continue_cmd+=(--milestone "$MILESTONE")
fi

continuation_prompt="$(MOSAIC_COORD_RUNTIME="$runtime" "${continue_cmd[@]}")"

if [[ "$runtime" == "codex" ]]; then
  launch_prompt="$(build_codex_strict_kickoff "$PROJECT" "$continuation_prompt")"
else
  launch_prompt="$continuation_prompt"
fi

if [[ "$PRINT" == true ]]; then
  echo "$launch_prompt"
  exit 0
fi

if [[ "$YOLO" == true ]]; then
  launch_cmd="mosaic yolo $runtime"
fi

echo -e "${C_CYAN}Launching orchestration runtime: ${launch_cmd}${C_RESET}"
echo -e "${C_CYAN}Project:${C_RESET} $PROJECT"
echo -e "${C_CYAN}Capsule:${C_RESET} $(next_task_capsule_path "$PROJECT")"
[[ "$YOLO" == true ]] && echo -e "${C_YELLOW}[YOLO] Dangerous permissions mode enabled.${C_RESET}"

cd "$PROJECT"
if [[ "$YOLO" == true ]]; then
  exec mosaic yolo "$runtime" "$launch_prompt"
elif [[ "$runtime" == "claude" ]]; then
  exec mosaic claude "$launch_prompt"
elif [[ "$runtime" == "codex" ]]; then
  exec mosaic codex "$launch_prompt"
fi

echo -e "${C_RED}Unsupported coord runtime: $runtime${C_RESET}" >&2
exit 1
