#!/usr/bin/env bash
# intern-qa workspace：
#   knowledge/ — 只读 symlink → $(dirname "$WS")/knowledge（与 intern-admin 工作区并列时即为共享知识库）
#   records/ — **本地目录**，日报按日 *.md、请假统一 leave.md，由答疑侧写入；相对 intern-admin 为 workspace-intern-qa/records/，**不做软链**
# 实例内 memory/、MEMORY.md 等仍在本 workspace，不由本脚本链接。
#
# 用法：安装器 post_install 调用；或：
#   WORKSPACE=/path/to/workspace-intern-qa ./scripts/setup_links.sh
#   OPENCLAW_WORKSPACE=... ./scripts/setup_links.sh
#   ./scripts/setup_links.sh /path/to/workspace-intern-qa
#
# 须先安装 intern-admin，保证父级目录下已有 knowledge/。

set -euo pipefail

WS="${WORKSPACE:-${OPENCLAW_WORKSPACE:-${1:-}}}"
if [[ -z "$WS" ]]; then
  echo "setup_links: set WORKSPACE or OPENCLAW_WORKSPACE, or pass the first argument as workspace root." >&2
  exit 1
fi

WS="$(cd "$WS" && pwd)"
parent="$(dirname "$WS")"
mkdir -p "$WS"

_link_one() {
  local name="$1"
  local src="${parent}/${name}"
  local link="${WS}/${name}"

  if [[ ! -d "$src" ]]; then
    echo "setup_links: ${name} directory not found: ${src}" >&2
    echo "setup_links: install intern-admin first and ensure ${src} exists." >&2
    exit 1
  fi

  if [[ -e "$link" && ! -L "$link" ]]; then
    echo "setup_links: ${link} exists and is not a symlink; refusing to replace." >&2
    exit 1
  fi

  rm -f "$link"
  ln -sfn "$(cd "$src" && pwd)" "$link"
  echo "setup_links: ${link} -> $(readlink "$link")"
}

_link_one "knowledge"

rec="${WS}/records"
if [[ -L "$rec" ]]; then
  rm -f "$rec"
fi
mkdir -p "$rec"
echo "setup_links: ${rec} (local directory)"
