#!/usr/bin/env bash
# Set up post-compaction context refresh rules in personal ~/.agents/AGENTS.md
# Usage: bash setup.sh
# Safe to run multiple times.

set -euo pipefail

PERSONAL_AGENTS="$HOME/.agents/AGENTS.md"

GREEN='\033[0;32m'
YELLOW='\033[1;33m'
CYAN='\033[0;36m'
BOLD='\033[1m'
RESET='\033[0m'

echo ""
echo -e "${BOLD}━━━ Compact Context Setup ━━━${RESET}"
echo ""

mkdir -p "$HOME/.agents"
[ -f "$PERSONAL_AGENTS" ] || : > "$PERSONAL_AGENTS"

PYTHON_OUTPUT="$(python3 - "$PERSONAL_AGENTS" <<'PY'
import pathlib
import re
import sys

path = pathlib.Path(sys.argv[1])
text = path.read_text(encoding="utf-8") if path.exists() else ""

startup_block = """## Session Startup

Context may have been compacted. When you see `[Post-compaction context refresh]` in your context:
1. Re-read any task files mentioned in the conversation before responding.
2. Treat missing earlier conversation details as incomplete context, not as proof they never happened.
3. If you need to mention compaction to the user, describe it naturally; do not force a fixed reply prefix.
"""

red_lines_block = """## Red Lines

- After compaction, re-read task context files before proceeding.
- Never assume conversation history is complete after a `[Post-compaction context refresh]`.
- Do not force a fixed reply prefix after compaction.
"""

legacy = "（已压缩，从摘要恢复）" in text or "Start your reply with:" in text

def upsert_section(source: str, title: str, block: str) -> tuple[str, bool]:
    pattern = rf"(?ms)^## {re.escape(title)}\n.*?(?=^## |\Z)"
    if re.search(pattern, source):
      return re.sub(pattern, block + "\n", source), True
    source = source.rstrip()
    if source:
      source += "\n\n"
    source += block + "\n"
    return source, False

updated, startup_exists = upsert_section(text, "Session Startup", startup_block)
updated, red_lines_exists = upsert_section(updated, "Red Lines", red_lines_block)
updated = updated.rstrip() + "\n"
path.write_text(updated, encoding="utf-8")

print(f"startup_exists={'1' if startup_exists else '0'}")
print(f"red_lines_exists={'1' if red_lines_exists else '0'}")
print(f"legacy={'1' if legacy else '0'}")
PY
)"

STARTUP_EXISTS="$(printf '%s\n' "$PYTHON_OUTPUT" | awk -F= '/^startup_exists=/{print $2}')"
RED_LINES_EXISTS="$(printf '%s\n' "$PYTHON_OUTPUT" | awk -F= '/^red_lines_exists=/{print $2}')"
LEGACY_FOUND="$(printf '%s\n' "$PYTHON_OUTPUT" | awk -F= '/^legacy=/{print $2}')"

if [ "$STARTUP_EXISTS" = "1" ]; then
  echo -e "${GREEN}✔ ## Session Startup updated${RESET} in $PERSONAL_AGENTS"
else
  echo -e "${GREEN}✔ ## Session Startup added${RESET} to $PERSONAL_AGENTS"
fi

if [ "$RED_LINES_EXISTS" = "1" ]; then
  echo -e "${GREEN}✔ ## Red Lines updated${RESET} in $PERSONAL_AGENTS"
else
  echo -e "${GREEN}✔ ## Red Lines added${RESET} to $PERSONAL_AGENTS"
fi

if [ "$LEGACY_FOUND" = "1" ]; then
  echo -e "${YELLOW}○ Legacy fixed-prefix rules were replaced with safer recovery guidance.${RESET}"
fi

echo ""
echo -e "${BOLD}Done.${RESET} Verify with: ${CYAN}bash check.sh${RESET}"
echo ""
echo -e "What happens next:"
echo -e "  • Every auto-compact can still re-inject your recovery rules"
echo -e "  • Agent will re-read task files after a context refresh"
echo -e "  • Replies are no longer forced to start with a fixed compaction prefix"
echo ""
