#!/bin/sh
# Texo one-line installer · https://github.com/mallorb/texo
# 它做三件事（全部可见、可逆）：
#   1. 把 texo-skill 的技能复制到 ~/.claude/skills/（你的 agent 因此学会编译 Texo）
#   2. 写 ~/.texo/compile.sh + launchd 定时任务（每 30 分钟无头编译一次）
#   3. 立刻跑第一轮编译
# 卸载：launchctl bootout gui/$(id -u)/com.texo.compile && rm -rf ~/.texo ~/.claude/skills/texo-*
set -e

FOLDER="$HOME/Library/Mobile Documents/iCloud~com~mallorb~texo/Documents/Texo"
REPO="${TEXO_REPO:-https://github.com/mallorb/texo}"
INTERVAL="${TEXO_INTERVAL:-1800}"   # 检查间隔（秒）；空转零成本，间隔只影响织入延迟

echo "Texo installer"
echo "──────────────"

CLAUDE_BIN=$(command -v claude || true)
if [ -z "$CLAUDE_BIN" ]; then
  echo "✗ 需要 Claude Code CLI（https://claude.com/claude-code），装好后重跑本脚本。"
  exit 1
fi
echo "✓ Claude Code: $CLAUDE_BIN"

if [ ! -d "$FOLDER" ]; then
  echo "✗ 未发现 Texo 文件夹。请先在 iPhone 上打开 Texo（确保已登录 iCloud），等一分钟同步后重跑。"
  echo "  预期位置：$FOLDER"
  exit 1
fi
echo "✓ Texo 文件夹已同步"

# 1) 安装技能
if [ -d "$REPO" ]; then
  SRC="$REPO"
else
  SRC=$(mktemp -d)
  git clone --quiet --depth 1 "$REPO" "$SRC"
fi
mkdir -p "$HOME/.claude/skills"
for s in import ingest compile lint answer review profile watch; do
  rm -rf "$HOME/.claude/skills/texo-$s"
  cp -R "$SRC/texo-skill/skills/$s" "$HOME/.claude/skills/texo-$s"
done
echo "✓ 技能已安装（~/.claude/skills/texo-*）"

# 2) launchd 自动编译（带零 token 预检：没活干不唤醒 agent）
mkdir -p "$HOME/.texo"
cat > "$HOME/.texo/compile.sh" <<SH
#!/bin/sh
FOLDER="$FOLDER"
cd "\$FOLDER" || exit 1
STATE="\$FOLDER/.texo/compile-state.json"

# 预检 1：存在未编译条目才继续（纯文件系统，零 token；子 shell exit 1 = 发现新条目）
if find "\$FOLDER/raw" -name '*.md' ! -name '*.desc.md' ! -name '*.transcript.md' 2>/dev/null \
  | while read -r f; do
      id=\$(basename "\$f" .md)
      grep -q "\"\$id\"" "\$STATE" 2>/dev/null || exit 1
    done; then
  exit 0  # 没有新条目
fi

# 预检 2：最新条目落盘不足 5 分钟则等下一轮（凑批，摊薄每次唤醒的固定开销）
RECENT=\$(find "\$FOLDER/raw" -name '*.md' -mmin -5 2>/dev/null | head -1)
[ -n "\$RECENT" ] && exit 0

echo "[\$(date '+%F %T')] new entries found, compiling…" >> "$HOME/.texo/compile.log"
exec "$CLAUDE_BIN" -p "依次执行 texo-ingest 与 texo-compile 处理本目录的新条目；无新条目则直接结束。" \
  --permission-mode acceptEdits >> "$HOME/.texo/compile.log" 2>&1
SH
chmod +x "$HOME/.texo/compile.sh"

PLIST="$HOME/Library/LaunchAgents/com.texo.compile.plist"
mkdir -p "$HOME/Library/LaunchAgents"
cat > "$PLIST" <<XML
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0"><dict>
  <key>Label</key><string>com.texo.compile</string>
  <key>ProgramArguments</key><array><string>$HOME/.texo/compile.sh</string></array>
  <key>StartInterval</key><integer>$INTERVAL</integer>
  <key>RunAtLoad</key><true/>
  <key>StandardOutPath</key><string>$HOME/.texo/launchd.log</string>
  <key>StandardErrorPath</key><string>$HOME/.texo/launchd.log</string>
</dict></plist>
XML
launchctl bootout "gui/$(id -u)/com.texo.compile" 2>/dev/null || true
launchctl bootstrap "gui/$(id -u)" "$PLIST"
echo "✓ 自动编译已启用（每 30 分钟；日志 ~/.texo/compile.log）"

# 3) 立刻跑第一轮
echo "→ 正在跑第一轮编译（首次可能需要几分钟）…"
launchctl kickstart "gui/$(id -u)/com.texo.compile"
echo ""
echo "完成。回到 iPhone 上的 Texo，「编译动态」很快会出现新页面。"
echo "进阶（在 Claude Code 里说）：「导入我的 Apple Notes 到 Texo」「生成我的 Texopedia 主页」"
