#!/bin/sh
# Installs portal's architecture skill into this repo, for any coding agent:
#
#   curl -fsSL https://portal-staging.haris-d21.workers.dev/install | sh
#
# - .claude/skills/portal-architecture/{SKILL.md,check.mjs}: the skill (Agent Skills format; Claude Code loads it)
#   and `portal check`.
# - A short pointer to it in AGENTS.md (created if missing; read by Codex, Cursor, Copilot's coding agent, Gemini CLI,
#   Amp and others), and in .github/copilot-instructions.md, GEMINI.md and .cursor/rules/ when the repo uses them.
#
# Run it again to update; it replaces its own marked block instead of adding another. Commit what it lists.
set -eu

PORTAL="${PORTAL_URL:-https://portal-staging.haris-d21.workers.dev}"
DIR=.claude/skills/portal-architecture
START="<!-- portal-architecture:start -->"
END="<!-- portal-architecture:end -->"

root=$(git rev-parse --show-toplevel 2>/dev/null) || { echo "portal: run this inside a git repository" >&2; exit 1; }
cd "$root"

mkdir -p "$DIR"
for f in SKILL.md check.mjs; do
  curl -fsSL "$PORTAL/skills/portal-architecture/$f" -o "$DIR/$f.tmp"
  mv "$DIR/$f.tmp" "$DIR/$f"
done
echo "portal: wrote $DIR/SKILL.md, $DIR/check.mjs"

BLOCK="$START
## Architecture model (portal)

This repo's architecture is described in \`architecture/*.c4\` (LikeC4) and checked by portal on every pull request.
When you change code, keep the model in step: follow \`$DIR/SKILL.md\`, and before pushing run
\`node $DIR/check.mjs\`; it prints the checks portal will post, and \"Nothing to act on\" means you're done.
$END"

# Puts the block into a file, replacing an earlier one.
upsert() {
  file=$1
  mkdir -p "$(dirname "$file")"
  if [ -f "$file" ] && grep -qF "$START" "$file"; then
    BLOCK="$BLOCK" awk -v s="$START" -v e="$END" '
      $0 == s { print ENVIRON["BLOCK"]; skip = 1; next }
      $0 == e { skip = 0; next }
      !skip { print }
    ' "$file" > "$file.tmp" && mv "$file.tmp" "$file"
    echo "portal: updated $file"
  else
    if [ -s "$file" ]; then printf '\n%s\n' "$BLOCK" >> "$file"; else printf '%s\n' "$BLOCK" > "$file"; fi
    echo "portal: added to $file"
  fi
}

upsert AGENTS.md
[ -f .github/copilot-instructions.md ] && upsert .github/copilot-instructions.md
[ -f GEMINI.md ] && upsert GEMINI.md
if [ -d .cursor ]; then
  mkdir -p .cursor/rules
  cat > .cursor/rules/portal-architecture.mdc <<EOF
---
description: Keep architecture/*.c4 in step with the code (portal)
alwaysApply: true
---
Follow $DIR/SKILL.md. Before pushing, run \`node $DIR/check.mjs\` and act on what it reports.
EOF
  echo "portal: wrote .cursor/rules/portal-architecture.mdc"
fi

echo "portal: done. Commit these files so every agent working in the repo picks them up."
