#!/usr/bin/env bash

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
STATE_FILE="$SCRIPT_DIR/codex_context.yaml"
INITIAL_INSTRUCTION="Before doing any task, read codex_context.yaml and treat it as shared project memory."
MEMORY_POLICY_PROMPT=$(cat <<'EOF'
You are an autonomous coding agent with persistent memory.

GOAL:
Continuously maintain and save a compressed, lossless SESSION_STATE to disk.

RULES:

1. After every meaningful change or decision:
   - Update SESSION_STATE
   - Save it to file: ./codex_context.yaml

2. SESSION_STATE must be:
   - Lossless (no important info lost)
   - Compressed (no fluff, structured)

FORMAT:

SESSION_STATE:
  meta:
    goal:
    environment:
  systems:
  configs:
  decisions:
  todos:
  issues:

3. Compression rules:
   - No natural language fluff
   - Use short keys
   - Deduplicate
   - Use IDs (S1, CFG1, etc.)

4. File operations:
   - Always overwrite ./codex_context.yaml
   - Ensure valid YAML
   - Never delete info unless explicitly told

5. On startup:
   - If ./codex_context.yaml exists -> load and use it as memory

6. Commands:

EXPORT STATE -> print file content only
IMPORT STATE -> load given YAML

7. Never ask for confirmation when saving context.

Act like a stateful system, not a stateless chat.
EOF
)

usage() {
  cat <<'EOF'
Usage: ./start-codex.sh [--print-prompt] [codex-args...]

Starts Codex in this repository with the persistent-memory bootstrap prompt.

Options:
  --print-prompt  Print the generated startup prompt and exit.
  -h, --help      Show this help and exit.

Examples:
  ./start-codex.sh
  ./start-codex.sh --full-auto
  ./start-codex.sh --model gpt-5.4
  ./start-codex.sh --print-prompt
EOF
}

build_prompt() {
  printf '%s\n\n' "$INITIAL_INSTRUCTION"
  printf '%s\n\n' "$MEMORY_POLICY_PROMPT"

  if [[ -f "$STATE_FILE" ]]; then
    printf '%s\n\n' 'Load SESSION_STATE below as full context. Treat it as authoritative memory. Continue work accordingly.'
    cat "$STATE_FILE"
    printf '\n'
  fi
}

main() {
  local print_prompt=0
  local -a codex_args=()

  while (($# > 0)); do
    case "$1" in
      --print-prompt)
        print_prompt=1
        shift
        ;;
      -h|--help)
        usage
        exit 0
        ;;
      *)
        codex_args+=("$1")
        shift
        ;;
    esac
  done

  local prompt
  prompt="$(build_prompt)"

  if ((print_prompt)); then
    printf '%s' "$prompt"
    exit 0
  fi

  cd "$SCRIPT_DIR"
  printf 'Loading %s\n' "$STATE_FILE"
  exec codex --cd "$SCRIPT_DIR" "${codex_args[@]}" "$prompt"
}

main "$@"
