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

ROOT="$(cd "$(dirname "$0")/../.." && pwd)"
KNOW="$ROOT/knowledge"
TODAY="$(date +%F)"
YDAY="$(date -v-1d +%F 2>/dev/null || date -d 'yesterday' +%F)"
DAILY="$KNOW/daily/$TODAY.md"
MEM_TODAY="$ROOT/memory/$TODAY.md"
MEM_YDAY="$ROOT/memory/$YDAY.md"
CORRECTIONS="$KNOW/rules/corrections-log.md"

mkdir -p "$KNOW/daily" "$KNOW/archive" "$KNOW/projects" "$KNOW/playbooks" "$KNOW/entities" "$KNOW/rules"

if [[ ! -f "$DAILY" ]]; then
  cat > "$DAILY" <<EOF
# Daily Note — $TODAY

## Key Events
- 

## Decisions
- 

## Promotions (to durable knowledge)
- 

## Open Loops
- 

## Candidate Promotions (auto)
- 
EOF
fi

# Build candidate promotion lines from memory notes (today + yesterday)
CANDIDATES_TMP="$(mktemp)"
{
  [[ -f "$MEM_YDAY" ]] && grep -Ein "remember|preference|rule|policy|decision|routing|thread|always|never|confirm|deadline|owner|assigned" "$MEM_YDAY" || true
  [[ -f "$MEM_TODAY" ]] && grep -Ein "remember|preference|rule|policy|decision|routing|thread|always|never|confirm|deadline|owner|assigned" "$MEM_TODAY" || true
} | sed -E 's#^.*/memory/##' | head -n 30 > "$CANDIDATES_TMP"

OPEN_CORRECTIONS_TMP="$(mktemp)"
if [[ -f "$CORRECTIONS" ]]; then
  grep -E "^- \[ \]" "$CORRECTIONS" | head -n 20 > "$OPEN_CORRECTIONS_TMP" || true
fi

# Replace auto block in daily note
awk -v ts="$(date '+%Y-%m-%d %H:%M:%S %Z')" \
    -v cfile="$CANDIDATES_TMP" \
    -v ofile="$OPEN_CORRECTIONS_TMP" '
BEGIN {
  print_mode=1
}
{
  if ($0 ~ /^<!-- AUTO_PROMOTIONS_START -->$/) {print_mode=0; next}
  if (print_mode==1) print $0
  if ($0 ~ /^<!-- AUTO_PROMOTIONS_END -->$/) {print_mode=1; next}
}
END {
  print ""
  print "<!-- AUTO_PROMOTIONS_START -->"
  print "## Candidate Promotions (auto)"
  print "_Generated: " ts "_"
  print ""
  print "### From memory/* (today + yesterday)"
  while ((getline line < cfile) > 0) {
    print "- " line
    seen=1
  }
  if (!seen) print "- None detected"
  print ""
  print "### Open corrections"
  seen2=0
  while ((getline line2 < ofile) > 0) {
    print "- " substr(line2,7)
    seen2=1
  }
  if (!seen2) print "- None"
  print "<!-- AUTO_PROMOTIONS_END -->"
}
' "$DAILY" > "$DAILY.tmp"

mv "$DAILY.tmp" "$DAILY"
rm -f "$CANDIDATES_TMP" "$OPEN_CORRECTIONS_TMP"

"$ROOT/scripts/memory/index.sh" >/dev/null

# Pending promotions sync (intent-bearing items must be resolved)
PENDING_OUT="$KNOW/daily/.pending-promotions-$TODAY.tmp"
set +e
PENDING_COUNT="$($ROOT/scripts/memory/pending-promotions-sync.py 2>/dev/null)"
PENDING_RC=$?
set -e
[[ -z "${PENDING_COUNT:-}" ]] && PENDING_COUNT=0

# Phase C: critical-facts retrieval checks
CHECK_OUT="$KNOW/daily/.critical-facts-$TODAY.tmp"
set +e
"$ROOT/scripts/memory/critical-facts-check.py" > "$CHECK_OUT" 2>&1
CHECK_RC=$?
set -e

awk -v cfile="$CHECK_OUT" -v pcount="$PENDING_COUNT" '
BEGIN { print_mode=1 }
{
  if ($0 ~ /^<!-- AUTO_CRITICAL_FACTS_START -->$/) {print_mode=0; next}
  if ($0 ~ /^<!-- AUTO_CRITICAL_FACTS_END -->$/) {print_mode=1; next}
  if ($0 ~ /^<!-- AUTO_PENDING_STATUS_START -->$/) {print_mode=0; next}
  if ($0 ~ /^<!-- AUTO_PENDING_STATUS_END -->$/) {print_mode=1; next}
  if (print_mode==1) print $0
}
END {
  print ""
  print "<!-- AUTO_PENDING_STATUS_START -->"
  print "## Pending Promotion Status (auto)"
  print "- Open pending promotions: " pcount
  if (pcount+0 > 0) print "- Conversation intent status: OPEN (resolve or dismiss pending items before closure)"
  else print "- Conversation intent status: CLEAR"
  print "<!-- AUTO_PENDING_STATUS_END -->"
  print ""
  print "<!-- AUTO_CRITICAL_FACTS_START -->"
  print "## Critical Facts Retrieval Check (auto)"
  while ((getline line < cfile) > 0) print line
  print "<!-- AUTO_CRITICAL_FACTS_END -->"
}
' "$DAILY" > "$DAILY.tmp2"
mv "$DAILY.tmp2" "$DAILY"
rm -f "$CHECK_OUT"

if [[ $PENDING_RC -ne 0 ]]; then
  echo "Consolidation completed with pending-promotions sync FAILURE: $TODAY" >&2
  exit $PENDING_RC
fi

if [[ $CHECK_RC -ne 0 ]]; then
  echo "Consolidation completed with critical-facts check FAILURE: $TODAY" >&2
  exit $CHECK_RC
fi

if [[ ${PENDING_COUNT:-0} -gt 0 ]]; then
  echo "Consolidation completed with OPEN pending promotions: $PENDING_COUNT" >&2
  exit 2
fi

echo "Consolidation complete: $TODAY"
