#!/usr/bin/env bash
set -euo pipefail

# Conservative workflow context hook for Polytoken.
# Handles session_start, pre_model_turn, and post_compaction.
# It injects compact framing only; it does not enforce gates yet.

EVENT="${POLYTOKEN_HOOK_EVENT:-}"
PROJECT_DIR="${POLYTOKEN_PROJECT_DIR:-${POLYTOKEN_PROJECT_PATH:-$(pwd)}}"
SESSION_ID="${POLYTOKEN_SESSION_ID:-}"

read_stdin() {
  cat >/tmp/polytoken-workflow-hook-stdin-$$.json || true
}

json_escape() {
  jq -Rs .
}

find_port() {
  if [ -z "$SESSION_ID" ]; then
    return 1
  fi
  local data_home session_dir startup
  data_home="${XDG_DATA_HOME:-${HOME:-}/.local/share}"
  if [ -z "$data_home" ]; then
    return 1
  fi
  session_dir="$data_home/polytoken/sessions/$SESSION_ID"
  startup="$session_dir/startup.json"
  if [ ! -f "$startup" ]; then
    return 1
  fi
  jq -r '.port // empty' "$startup"
}

state_summary() {
  local port="$1"
  curl -fsS "http://127.0.0.1:${port}/state" 2>/dev/null \
    | jq -r '
        "- Active facet: \(.active_facet // "unknown")\n" +
        "- Active model: \(.active_model // "unknown")\n" +
        "- Project cwd: \(.project_cwd // "unknown")\n" +
        "- Todos: \((.todos // []) | length)\n" +
        "- Flags: \((.flags // []) | length)"
      ' 2>/dev/null || true
}

project_vars_summary() {
  local vars="$PROJECT_DIR/.polytoken/project_vars.yaml"
  if [ ! -f "$vars" ]; then
    printf '%s\n' "- Project vars: none found at .polytoken/project_vars.yaml"
    return 0
  fi

  printf '%s\n' "- Project vars: .polytoken/project_vars.yaml"
  if command -v yq >/dev/null 2>&1; then
    return 0
  fi
  # Avoid depending on yq. Report the file exists; facets render the details.
}

active_gates_summary() {
  local gates_dir="$PROJECT_DIR/agent_docs/.workflow/gates"
  local alt_gates_dir="$PROJECT_DIR/docs/polytoken-workflows/.workflow/gates"
  local found=0

  for dir in "$gates_dir" "$alt_gates_dir"; do
    if [ -d "$dir" ]; then
      local count
      count=$(find "$dir" -maxdepth 1 -type f -name '*.json' 2>/dev/null | wc -l | tr -d ' ')
      if [ "${count:-0}" != "0" ]; then
        printf '%s\n' "- Active workflow gate files: $count in ${dir#$PROJECT_DIR/}"
        found=1
      fi
    fi
  done

  if [ "$found" = 0 ]; then
    printf '%s\n' "- Active workflow gates: none detected"
  fi
}

build_context() {
  local port="" state=""
  port="$(find_port || true)"
  if [ -n "$port" ]; then
    state="$(state_summary "$port")"
  fi

  cat <<EOF
<workflow-context>
Polytoken workflow framing:
$(project_vars_summary)
${state:-"- Daemon state: unavailable from hook"}
$(active_gates_summary)

Use project-specific design workflow instructions from project_vars when present. Distinguish human source of truth from agent working truth. In design/plan work, keep durable documents focused on current state and link to history rather than carrying stale content inline.
</workflow-context>
EOF
}

read_stdin
context="$(build_context)"

case "$EVENT" in
  session_start)
    jq -n --arg ctx "$context" '{outcome:"allow", additional_context:$ctx}'
    ;;
  pre_model_turn)
    jq -n --arg ctx "$context" '{outcome:"proceed", additional_context:$ctx}'
    ;;
  post_compaction)
    jq -n --arg ctx "$context" '{outcome:"allow", append_to_output:$ctx}'
    ;;
  *)
    jq -n '{outcome:"allow"}'
    ;;
esac
