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

LANEKEEP_DIR="${LANEKEEP_DIR:-$(cd "$(dirname "$0")/.." && pwd)}"
PROJECT_DIR="${PROJECT_DIR:-$(pwd 2>/dev/null || echo "$PWD")}"
TRACE_DIR="$PROJECT_DIR/.lanekeep/traces"

# --- summary subcommand (cost-line / json exporter for PR bodies & tooling) ---
if [ "${1:-}" = "--summary" ]; then
  shift
  mode="${1:-}"
  case "$mode" in
    cost-line|json) shift ;;
    "") echo "Usage: lanekeep-trace --summary {cost-line|json} [--task <id>|--session <id>] [--with-savings]" >&2; exit 2 ;;
    *)  echo "Unknown --summary mode: $mode (expected: cost-line, json)" >&2; exit 2 ;;
  esac

  scope="" scope_id="" with_savings=0
  while [ $# -gt 0 ]; do
    case "$1" in
      --task)         shift; scope="task";    scope_id="${1:-}"; shift ;;
      --session)      shift; scope="session"; scope_id="${1:-}"; shift ;;
      --with-savings) with_savings=1; shift ;;
      *) echo "Unknown --summary option: $1" >&2; exit 2 ;;
    esac
  done

  # Scope resolution: explicit flag > env var > default to "session" (current)
  if [ -z "$scope" ]; then
    if [ -n "${LANEKEEP_TASK_ID:-}" ]; then
      scope="task";    scope_id="$LANEKEEP_TASK_ID"
    elif [ -n "${LANEKEEP_SESSION_ID:-}" ]; then
      scope="session"; scope_id="$LANEKEEP_SESSION_ID"
    else
      scope="session"; scope_id=""
    fi
  fi

  # shellcheck source=/dev/null
  . "$LANEKEEP_DIR/lib/cost-line.sh"
  if [ "$mode" = "cost-line" ]; then
    cost_line::emit_cost_line "$scope" "$scope_id" "$with_savings"
  else
    cost_line::emit_json "$scope" "$scope_id"
  fi
  exit $?
fi

# --- clear subcommand ---
if [ "${1:-}" = "clear" ]; then
  # shellcheck source=/dev/null
  source "$LANEKEEP_DIR/lib/trace.sh"
  shift

  retention_days=0
  max_sessions=0
  keep_current=true

  while [ $# -gt 0 ]; do
    case "$1" in
      --older-than)
        shift
        # Parse duration: strip trailing 'd', require integer
        val="${1:-}"
        val="${val%d}"
        if ! [[ "$val" =~ ^[0-9]+$ ]]; then
          echo "Invalid duration: ${1:-}. Use e.g. 7d or 30d." >&2
          exit 1
        fi
        retention_days="$val"
        keep_current=true
        shift
        ;;
      --all)
        retention_days=0
        max_sessions=0
        keep_current=false
        shift
        ;;
      *)
        echo "Unknown option: $1" >&2
        exit 1
        ;;
    esac
  done

  if [ ! -d "$TRACE_DIR" ]; then
    echo "No trace files found."
    exit 0
  fi

  # Log the clear event (best-effort)
  if [ -n "${LANEKEEP_TRACE_FILE:-}" ]; then
    write_policy_event "trace_clear" "" "maintenance" "${USER:-unknown}" \
      "retention_days=$retention_days max_sessions=$max_sessions keep_current=$keep_current" || true
  fi

  prune_traces "$TRACE_DIR" "$retention_days" "$max_sessions" "$keep_current" "${LANEKEEP_SESSION_ID:-}"

  if [ "$PRUNE_DELETED" -eq 0 ]; then
    echo "No trace files to clear."
  else
    # Human-readable size
    if [ "$PRUNE_FREED_BYTES" -ge 1048576 ]; then
      freed="$((PRUNE_FREED_BYTES / 1048576)) MB"
    elif [ "$PRUNE_FREED_BYTES" -ge 1024 ]; then
      freed="$((PRUNE_FREED_BYTES / 1024)) KB"
    else
      freed="$PRUNE_FREED_BYTES bytes"
    fi
    echo "Cleared $PRUNE_DELETED file(s), freed $freed."
  fi
  exit 0
fi

# --- view subcommand (existing behavior) ---

# Find latest trace file
if [ ! -d "$TRACE_DIR" ]; then
  echo "No trace files found in $TRACE_DIR" >&2
  exit 1
fi

# Safe file discovery: avoid parsing ls output (M3)
LATEST=""
while IFS= read -r -d '' f; do
  if [ -z "$LATEST" ] || [ "$f" -nt "$LATEST" ]; then
    LATEST="$f"
  fi
done < <(find "$TRACE_DIR" -maxdepth 1 -name '*.jsonl' -print0 2>/dev/null)

if [ -z "$LATEST" ]; then
  echo "No trace files found in $TRACE_DIR" >&2
  exit 1
fi

case "${1:-}" in
  --follow)
    tail -f "$LATEST" | jq --unbuffered -c '.'
    ;;
  --all)
    jq '.' "$LATEST"
    ;;
  --filter)
    jq --arg dec "${2:-deny}" 'select(.decision == $dec)' "$LATEST"
    ;;
  *)
    tail -n 50 "$LATEST" | jq '.'
    ;;
esac
