#!/usr/bin/env bash
# compute-state: Scan room/ directory and output STATE.md content
# Called by session-start and on-stop hooks
# Outputs structured markdown to stdout

set -euo pipefail

# Cross-platform find with modification time (outputs: epoch.fractional filepath)
# Replaces GNU find -printf '%T@ %p\n' which is not available on macOS
portable_find_mtime() {
  # All arguments are passed to find, but -printf is NOT used
  # Instead, use -exec with stat to get modification time
  if [ "$(uname -s)" = "Darwin" ]; then
    find "$@" -exec stat -f '%m %N' {} \;
  else
    find "$@" -printf '%T@ %p\n'
  fi
}

ROOM_DIR="${1:-.}"

if [ ! -d "$ROOM_DIR" ]; then
  echo "# Data Room State"
  echo ""
  echo "No room directory found."
  exit 0
fi

# Quick 260723-ad9: durability half of the statusline current_room contract.
# scripts/on-agent-complete runs `compute-state "$ROOM_DIR" > STATE.md`, and the
# shell truncates STATE.md to zero BEFORE this script runs, so the event-driven
# write (room-registry) cannot survive by reading the room's own now-empty file.
# Re-derive current_room from the registry (the only truncation-safe source),
# and ONLY when the room being computed IS the registry's active room. A
# non-active room prints an empty slug and gains NO current_room line, so this
# never bulk-backfills the existing rooms.
ROOMS_HOME="${MINDRIAN_ROOMS_HOME:-$HOME/MindrianRooms}"
CURRENT_ROOM_SLUG=$(ROOMS_HOME="$ROOMS_HOME" ROOM_DIR="$ROOM_DIR" python3 - <<'PY_EOF' 2>/dev/null || true
import json, os, sys
home = os.environ.get('ROOMS_HOME', '')
room_dir = os.environ.get('ROOM_DIR', '')
reg_path = os.path.join(home, '.rooms', 'registry.json')
try:
    with open(reg_path) as f:
        reg = json.load(f)
except Exception:
    sys.exit(0)  # missing/corrupt registry: degrade, never abort compute-state
if not isinstance(reg, dict):
    sys.exit(0)
active = reg.get('active', '')
if not active:
    sys.exit(0)
rooms = reg.get('rooms', {})
entry = rooms.get(active, {}) if isinstance(rooms, dict) else {}
if not isinstance(entry, dict):
    entry = {}
# Same 3-tier precedence as the read/list/bootstrap-missing stanzas.
abs_path = entry.get('abs_path')
if not abs_path:
    p = entry.get('path')
    if p and os.path.isabs(p):
        abs_path = p
    elif p:
        abs_path = os.path.join(home, p)
    else:
        abs_path = os.path.join(home, active)
try:
    if os.path.realpath(abs_path) == os.path.realpath(room_dir):
        print(active)
except Exception:
    sys.exit(0)
PY_EOF
)

# Collect section data
declare -a section_names=()
declare -a section_entries=()
declare -a section_statuses=()
declare -a section_dates=()
total_entries=0

# Plan 80-05 Task 2: dynamic section discovery confirmed.
# This glob walks every top-level folder under room/, so inbox/ (with its
# suggested/ and unclassified/ sub-branches added by Phase 80 vault-import)
# is picked up automatically without any hard-coded section list.
for section_dir in "$ROOM_DIR"/*/; do
  [ -d "$section_dir" ] || continue
  section_name=$(basename "$section_dir")

  # Skip hidden directories and special files
  [[ "$section_name" == .* ]] && continue

  section_names+=("$section_name")

  # Count .md files excluding ROOM.md
  entry_count=$(find "$section_dir" -maxdepth 1 -name "*.md" ! -name "ROOM.md" 2>/dev/null | wc -l)
  entry_count=$(echo "$entry_count" | tr -d ' ')
  section_entries+=("$entry_count")
  total_entries=$((total_entries + entry_count))

  # Determine status
  if [ "$entry_count" -eq 0 ]; then
    section_statuses+=("Empty")
  elif [ "$entry_count" -ge 3 ]; then
    section_statuses+=("Well-developed")
  else
    section_statuses+=("Active")
  fi

  # Get last modified date of most recent .md file
  latest_file=$(portable_find_mtime "$section_dir" -maxdepth 1 -name "*.md" 2>/dev/null | sort -rn | head -1 | cut -d' ' -f2-)
  if [ -n "$latest_file" ]; then
    section_dates+=("$(date -r "$latest_file" +%Y-%m-%d 2>/dev/null || echo "unknown")")
  else
    section_dates+=("-")
  fi
done

# Infer venture stage from which sections have content
has_problem=false
has_market=false
has_solution=false
has_business=false
has_financial=false

for i in "${!section_names[@]}"; do
  count="${section_entries[$i]}"
  [ "$count" -eq 0 ] && continue
  case "${section_names[$i]}" in
    problem-definition) has_problem=true ;;
    market-analysis) has_market=true ;;
    solution-design) has_solution=true ;;
    business-model) has_business=true ;;
    financial-model) has_financial=true ;;
  esac
done

venture_stage="Pre-Opportunity"
if $has_problem && ! $has_market; then
  venture_stage="Pre-Opportunity"
elif $has_problem && $has_market && ! $has_solution; then
  venture_stage="Discovery"
elif $has_problem && $has_market && $has_solution && ! $has_business; then
  venture_stage="Validation"
elif $has_problem && $has_solution && $has_business && ! $has_financial; then
  venture_stage="Design"
elif $has_problem && $has_solution && $has_business && $has_financial; then
  venture_stage="Investment"
fi

# Count meetings
meeting_count=0
last_meeting_date=""
if [ -d "$ROOM_DIR/meetings" ]; then
  for meeting_dir in "$ROOM_DIR"/meetings/*/; do
    [ -d "$meeting_dir" ] || continue
    meeting_count=$((meeting_count + 1))
    dir_name=$(basename "$meeting_dir")
    # Extract date from YYYY-MM-DD-{name} format
    meeting_date="${dir_name:0:10}"
    if [[ "$meeting_date" > "$last_meeting_date" ]]; then
      last_meeting_date="$meeting_date"
    fi
  done
fi

# Count team members
team_count=0
if [ -d "$ROOM_DIR/team" ]; then
  team_count=$(find "$ROOM_DIR/team" -name "PROFILE.md" 2>/dev/null | wc -l | tr -d ' ')
fi

# Compute team intelligence (writes TEAM-STATE.md)
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
if [ -d "$ROOM_DIR/team" ] && [ "$team_count" -gt 0 ]; then
  bash "$SCRIPT_DIR/compute-team" "$ROOM_DIR" 2>/dev/null || true
fi

# Compute cross-meeting intelligence (writes MEETINGS-INTELLIGENCE.md + action-items.md)
if [ -d "$ROOM_DIR/meetings" ] && [ "$meeting_count" -gt 0 ]; then
  bash "$SCRIPT_DIR/compute-meetings-intelligence" "$ROOM_DIR" 2>/dev/null || true
fi

# Detect cross-references
declare -a cross_refs=()
for section_dir in "$ROOM_DIR"/*/; do
  [ -d "$section_dir" ] || continue
  section_name=$(basename "$section_dir")
  [[ "$section_name" == .* ]] && continue

  for md_file in "$section_dir"/*.md; do
    [ -f "$md_file" ] || continue
    fname=$(basename "$md_file")
    [ "$fname" = "ROOM.md" ] && continue

    # Look for [[section-name]] or room/section-name references
    for target in "${section_names[@]}"; do
      [ "$target" = "$section_name" ] && continue
      if grep -qE "\[\[$target\]\]|room/$target" "$md_file" 2>/dev/null; then
        cross_refs+=("${section_name}/${fname} references ${target}")
      fi
    done
  done
done

# ── Visual output generation (graceful degradation if visual-ops unavailable) ──
SECTIONS_JSON="["
for i in "${!section_names[@]}"; do
  [ "$i" -gt 0 ] && SECTIONS_JSON+=","
  SECTIONS_JSON+="{\"name\":\"${section_names[$i]}\",\"entryCount\":${section_entries[$i]},\"stage\":\"${venture_stage}\",\"edges\":[]}"
done
SECTIONS_JSON+="]"

ENTRY_COUNTS_JSON="["
for i in "${!section_entries[@]}"; do
  [ "$i" -gt 0 ] && ENTRY_COUNTS_JSON+=","
  ENTRY_COUNTS_JSON+="${section_entries[$i]}"
done
ENTRY_COUNTS_JSON+="]"

# Generate room diagram (Unicode box layout)
DIAGRAM=$(node -e "
  const v = require('$SCRIPT_DIR/../lib/core/visual-ops.cjs');
  const sections = JSON.parse(process.argv[1]);
  console.log(v.renderRoomDiagram(sections, { useColor: true }));
" "$SECTIONS_JSON" 2>/dev/null || echo "")

# Generate sparkline of section completeness
SPARKLINE=$(node -e "
  const v = require('$SCRIPT_DIR/../lib/core/visual-ops.cjs');
  const values = JSON.parse(process.argv[1]);
  console.log(v.renderSparkline(values, { height: 4, label: 'Section Completeness' }));
" "$ENTRY_COUNTS_JSON" 2>/dev/null || echo "")

# Build output
timestamp=$(date -u +"%Y-%m-%dT%H:%M:%SZ")

# Quick 260723-ad9: emit the frontmatter line-by-line so current_room is
# included ONLY for the registry-active room (empty slug -> no line, no
# backfill).
#
# CORRECTED (Phase 240.1 Plan 03, CTXL-01): this script is a PURE RENDER TO
# STDOUT and never reads the target file. The emitted frontmatter block
# below deliberately carries NO version stamp. Version preservation and
# persistence belong to lib/core/state-version.cjs::persistState, which
# every STATE.md write site must call -- either directly (Node callers) or
# via scripts/state-write.cjs (bash callers piping this script's stdout
# through it). A manual `bash scripts/compute-state <room> > STATE.md`
# bypasses persistState entirely and WILL drop the gsd_state_version and
# status stamps that scripts/room-registry seeds at room birth
# (240.1-RESEARCH.md Finding 1B). The old comment here read "because the
# block is emitted fresh, this cannot clobber siblings" -- that is true
# within this frontmatter block and false about the block as a whole,
# because the whole prior frontmatter is discarded by whatever caller
# redirects this script's output.
echo "---"
echo "computed: ${timestamp}"
echo "venture_stage: ${venture_stage}"
echo "total_entries: ${total_entries}"
[ -n "$CURRENT_ROOM_SLUG" ] && echo "current_room: ${CURRENT_ROOM_SLUG}"
echo "---"
echo "# Data Room State"
echo ""

# Visual summary first (diagram + sparkline), then details
if [ -n "$DIAGRAM" ]; then
  echo "## Room Map"
  echo ""
  echo "$DIAGRAM"
  echo ""
fi

if [ -n "$SPARKLINE" ]; then
  echo "$SPARKLINE"
  echo ""
fi

echo "## Sections"
echo "| Section | Entries | Progress | Status | Last Updated |"
echo "|---------|---------|----------|--------|-------------|"

# Determine max entries for progress bar scaling
max_entries=5
for i in "${!section_entries[@]}"; do
  [ "${section_entries[$i]}" -gt "$max_entries" ] && max_entries="${section_entries[$i]}"
done

for i in "${!section_names[@]}"; do
  # Generate progress bar for each section
  PROGRESS_BAR=$(node -e "
    const v = require('$SCRIPT_DIR/../lib/core/visual-ops.cjs');
    console.log(v.renderProgressBar(${section_entries[$i]}, ${max_entries}, 10));
  " 2>/dev/null || echo "${section_entries[$i]}/${max_entries}")
  echo "| ${section_names[$i]} | ${section_entries[$i]} | ${PROGRESS_BAR} | ${section_statuses[$i]} | ${section_dates[$i]} |"
done

echo ""

# Gaps section
echo "## Gaps"
has_gaps=false
for i in "${!section_names[@]}"; do
  if [ "${section_entries[$i]}" -eq 0 ]; then
    has_gaps=true
    case "${section_names[$i]}" in
      problem-definition) echo "- problem-definition: No entries. Start with /mos:new-project to define your core problem." ;;
      market-analysis) echo "- market-analysis: No entries. Consider exploring market size and customer segments." ;;
      solution-design) echo "- solution-design: No entries. Consider mapping your solution architecture." ;;
      business-model) echo "- business-model: No entries. Consider defining your revenue model." ;;
      competitive-analysis) echo "- competitive-analysis: No entries. Consider /mos:challenge-assumptions." ;;
      team-execution) echo "- team-execution: No entries. Consider documenting your team and execution plan." ;;
      legal-ip) echo "- legal-ip: No entries. Consider documenting legal structure and IP." ;;
      financial-model) echo "- financial-model: No entries. Consider building initial financial projections." ;;
      *) echo "- ${section_names[$i]}: No entries." ;;
    esac
  fi
done
if ! $has_gaps; then
  echo "No gaps detected -- all sections have entries."
fi

echo ""

# Cross-references section
echo "## Cross-References"
if [ ${#cross_refs[@]} -gt 0 ]; then
  for ref in "${cross_refs[@]}"; do
    echo "- $ref"
  done
else
  echo "No cross-references detected yet."
fi

echo ""

# Meetings section
if [ "$meeting_count" -gt 0 ]; then
  echo "## Meetings"
  echo ""
  echo "- **Meetings filed:** $meeting_count"
  echo "- **Last meeting:** $last_meeting_date"
  echo ""

  # Cross-Meeting Intelligence summary (from MEETINGS-INTELLIGENCE.md)
  if [ -f "$ROOM_DIR/MEETINGS-INTELLIGENCE.md" ]; then
    echo "## Cross-Meeting Intelligence"
    echo ""
    convergence_count=$(grep '^convergence_signals:' "$ROOM_DIR/MEETINGS-INTELLIGENCE.md" | sed 's/^convergence_signals: *//' || true)
    unresolved_count=$(grep '^unresolved_contradictions:' "$ROOM_DIR/MEETINGS-INTELLIGENCE.md" | sed 's/^unresolved_contradictions: *//' || true)
    open_items_count=$(grep '^open_action_items:' "$ROOM_DIR/MEETINGS-INTELLIGENCE.md" | sed 's/^open_action_items: *//' || true)
    [ -n "$convergence_count" ] && [ "$convergence_count" -gt 0 ] 2>/dev/null && echo "- **Active convergence signals:** $convergence_count"
    [ -n "$unresolved_count" ] && [ "$unresolved_count" -gt 0 ] 2>/dev/null && echo "- **Unresolved contradictions:** $unresolved_count"
    [ -n "$open_items_count" ] && [ "$open_items_count" -gt 0 ] 2>/dev/null && echo "- **Open action items:** $open_items_count"
    echo "- See room/MEETINGS-INTELLIGENCE.md for details"
    echo ""
  fi
fi

# Team section
if [ "$team_count" -gt 0 ]; then
  echo "## Team"
  echo ""
  echo "- **Team profiles:** $team_count"
  # Read roles from TEAM-STATE.md if available
  if [ -f "$ROOM_DIR/team/TEAM-STATE.md" ]; then
    roles_line=$(grep '^roles_represented:' "$ROOM_DIR/team/TEAM-STATE.md" | sed 's/^roles_represented: *//' || true)
    active_count=$(grep '^active_members:' "$ROOM_DIR/team/TEAM-STATE.md" | sed 's/^active_members: *//' || true)
    [ -n "$roles_line" ] && echo "- **Roles:** $roles_line"
    [ -n "$active_count" ] && echo "- **Active:** $active_count"
    # Show critical gaps if any
    gap_critical=$(grep 'CRITICAL' "$ROOM_DIR/team/TEAM-STATE.md" 2>/dev/null | head -3 || true)
    if [ -n "$gap_critical" ]; then
      echo "- **Knowledge gaps detected** -- see team/TEAM-STATE.md"
    fi
  fi
  echo ""
fi

# Suggested next action
echo "## Suggested Next Action"
if [ "$total_entries" -eq 0 ]; then
  echo "Your Data Room is empty. Run /mos:new-project to get started with Larry."
elif [ "$venture_stage" = "Pre-Opportunity" ]; then
  echo "You have early problem definition work. Explore your market to move to Discovery stage."
elif [ "$venture_stage" = "Discovery" ]; then
  echo "Problem and market are taking shape. Design your solution to move to Validation."
elif [ "$venture_stage" = "Validation" ]; then
  echo "Strong foundation. Define your business model to move to Design stage."
elif [ "$venture_stage" = "Design" ]; then
  echo "Nearly complete. Build financial projections to reach Investment readiness."
elif [ "$venture_stage" = "Investment" ]; then
  echo "Comprehensive Data Room. Review gaps and strengthen weak sections for investor readiness."
fi
