#!/usr/bin/env bash
# IF.story universal installer v2.4
# Works on: Linux, macOS, WSL, Windows (Git Bash/MSYS2)
# Targets: Codex CLI, Claude Code, or both (auto-detected)
set -euo pipefail

SCRIPT_SELF="${BASH_SOURCE[0]:-}"
if [ -n "$SCRIPT_SELF" ] && [ -f "$SCRIPT_SELF" ]; then
  SCRIPT_DIR="$(cd "$(dirname "$SCRIPT_SELF")" && pwd)"
else
  SCRIPT_DIR="$(pwd)"
fi
LOCAL_PAYLOAD_DIR="$SCRIPT_DIR/payload"
BASE_URL="${IFSTORY_INSTALL_BASE_URL:-https://infrafabric.io/skill/ifstory}"
WORK_DIR=""
ACTIVE_PAYLOAD_DIR=""

cleanup() {
  if [ -n "${WORK_DIR:-}" ] && [ -d "$WORK_DIR" ]; then
    rm -rf "$WORK_DIR"
  fi
}
trap cleanup EXIT

# ── Detect OS ──────────────────────────────────────────────────────────
detect_os() {
  case "$(uname -s)" in
    Linux*)
      if grep -qi microsoft /proc/version 2>/dev/null; then
        echo "wsl"
      else
        echo "linux"
      fi
      ;;
    Darwin*)  echo "macos" ;;
    CYGWIN*|MINGW*|MSYS*) echo "windows" ;;
    *)        echo "unknown" ;;
  esac
}

# ── Download helpers ───────────────────────────────────────────────────
download_file() {
  local url="$1"
  local dest="$2"
  if command -v curl >/dev/null 2>&1; then
    curl -fsSL "$url" -o "$dest"
    return
  fi
  if command -v wget >/dev/null 2>&1; then
    wget -qO "$dest" "$url"
    return
  fi
  echo "ERROR: Need curl or wget to download $url" >&2
  exit 1
}

fetch_payload_file() {
  local rel="$1"
  local dest="$2"
  mkdir -p "$(dirname "$dest")"
  if [ -f "$LOCAL_PAYLOAD_DIR/$rel" ]; then
    cp "$LOCAL_PAYLOAD_DIR/$rel" "$dest"
    return
  fi
  if download_file "$BASE_URL/payload/$rel" "$dest" 2>/dev/null; then
    return
  fi
  if download_file "$BASE_URL/$rel" "$dest" 2>/dev/null; then
    return
  fi
  echo "ERROR: Unable to fetch payload file $rel from $BASE_URL" >&2
  exit 1
}

prepare_payload_dir() {
  if [ -f "$LOCAL_PAYLOAD_DIR/SKILL.md" ] && [ -f "$LOCAL_PAYLOAD_DIR/IF.story.md" ]; then
    ACTIVE_PAYLOAD_DIR="$LOCAL_PAYLOAD_DIR"
    return
  fi
  WORK_DIR="$(mktemp -d)"
  ACTIVE_PAYLOAD_DIR="$WORK_DIR/payload"
  fetch_payload_file "SKILL.md" "$ACTIVE_PAYLOAD_DIR/SKILL.md"
  fetch_payload_file "IF.story.md" "$ACTIVE_PAYLOAD_DIR/IF.story.md"
}

# ── JSON helpers ───────────────────────────────────────────────────────
json_edit() {
  local mode="$1"
  local path="$2"
  shift 2
  if command -v python3 >/dev/null 2>&1; then
    python3 - "$mode" "$path" "$@" <<'PY'
import json, sys
mode = sys.argv[1]
path = sys.argv[2]
args = sys.argv[3:]

def load_json(path):
    try:
        with open(path, 'r', encoding='utf-8') as fh:
            text = fh.read().strip()
    except FileNotFoundError:
        return {}
    if not text:
        return {}
    try:
        data = json.loads(text)
    except Exception as exc:
        print(f"ERROR: invalid JSON in {path}: {exc}", file=sys.stderr)
        sys.exit(1)
    if not isinstance(data, dict):
        return {}
    return data

def dump_json(path, data):
    with open(path, 'w', encoding='utf-8') as fh:
        json.dump(data, fh, indent=2, sort_keys=True)
        fh.write('\n')

data = load_json(path)
if mode == 'known_marketplace':
    mkt_dir, ts = args
    data['local'] = {
        'source': {'source': 'directory', 'path': mkt_dir},
        'installLocation': mkt_dir,
        'lastUpdated': ts,
    }
elif mode == 'installed_plugin':
    ts, = args
    plugins = data.get('plugins')
    if not isinstance(plugins, dict):
        plugins = {}
    plugins['ifstory@local'] = {'enabled': True, 'installedAt': ts}
    data['plugins'] = plugins
elif mode == 'enabled_plugin':
    enabled = data.get('enabledPlugins')
    if not isinstance(enabled, dict):
        enabled = {}
    enabled['ifstory@local'] = True
    data['enabledPlugins'] = enabled
else:
    print(f'ERROR: unknown json_edit mode {mode}', file=sys.stderr)
    sys.exit(1)
dump_json(path, data)
PY
    return
  fi
  if command -v node >/dev/null 2>&1; then
    node - "$mode" "$path" "$@" <<'JS'
const fs = require('fs');
const mode = process.argv[2];
const path = process.argv[3];
const args = process.argv.slice(4);
let data = {};
try {
  const raw = fs.existsSync(path) ? fs.readFileSync(path, 'utf8').trim() : '';
  data = raw ? JSON.parse(raw) : {};
} catch (err) {
  console.error(`ERROR: invalid JSON in ${path}: ${err.message}`);
  process.exit(1);
}
if (typeof data !== 'object' || data === null || Array.isArray(data)) data = {};
if (mode === 'known_marketplace') {
  const [mktDir, ts] = args;
  data.local = {
    source: { source: 'directory', path: mktDir },
    installLocation: mktDir,
    lastUpdated: ts,
  };
} else if (mode === 'installed_plugin') {
  const [ts] = args;
  if (typeof data.plugins !== 'object' || data.plugins === null || Array.isArray(data.plugins)) data.plugins = {};
  data.plugins['ifstory@local'] = { enabled: true, installedAt: ts };
} else if (mode === 'enabled_plugin') {
  if (typeof data.enabledPlugins !== 'object' || data.enabledPlugins === null || Array.isArray(data.enabledPlugins)) data.enabledPlugins = {};
  data.enabledPlugins['ifstory@local'] = true;
} else {
  console.error(`ERROR: unknown json_edit mode ${mode}`);
  process.exit(1);
}
fs.writeFileSync(path, JSON.stringify(data, null, 2) + '\n');
JS
    return
  fi
  echo "ERROR: Need python3 or node to edit JSON files safely" >&2
  exit 1
}

ensure_json_file() {
  local path="$1"
  local default_content="$2"
  if [ ! -f "$path" ]; then
    mkdir -p "$(dirname "$path")"
    printf '%s\n' "$default_content" > "$path"
  fi
}

OS="$(detect_os)"
prepare_payload_dir

# ── Detect available runtimes ──────────────────────────────────────────
HAS_CODEX=false
HAS_CLAUDE=false

CODEX_HOME="${CODEX_HOME:-$HOME/.codex}"
CLAUDE_HOME="${CLAUDE_HOME:-$HOME/.claude}"

[ -d "$CODEX_HOME" ] && HAS_CODEX=true
[ -d "$CLAUDE_HOME" ] && HAS_CLAUDE=true

# Allow forcing a specific target
TARGET="${1:-auto}"
case "$TARGET" in
  codex)  HAS_CODEX=true; HAS_CLAUDE=false ;;
  claude) HAS_CODEX=false; HAS_CLAUDE=true ;;
  both)   HAS_CODEX=true; HAS_CLAUDE=true ;;
  auto)   ;; # use detection
  *)
    echo "ERROR: Unknown target '$TARGET' (use auto|codex|claude|both)" >&2
    exit 1
    ;;
esac

if ! $HAS_CODEX && ! $HAS_CLAUDE; then
  echo "ERROR: No supported runtime found."
  echo "  Looked for: $CODEX_HOME (Codex) and $CLAUDE_HOME (Claude Code)"
  echo "  Set CODEX_HOME or CLAUDE_HOME, or pass 'codex'/'claude'/'both' as argument."
  exit 1
fi

echo "OS detected: $OS"
echo "Runtimes:    codex=$HAS_CODEX  claude=$HAS_CLAUDE"
echo "Source:      $BASE_URL"
echo ""

# ── Install for Codex ──────────────────────────────────────────────────
install_codex() {
  local skill_dir="$CODEX_HOME/skills/ifstory"
  mkdir -p "$skill_dir/references"
  cp "$ACTIVE_PAYLOAD_DIR/SKILL.md"    "$skill_dir/SKILL.md"
  cp "$ACTIVE_PAYLOAD_DIR/IF.story.md" "$skill_dir/references/IF.story.md"

  local agents_file="${AGENTS_FILE:-$HOME/AGENTS.md}"
  if [ -f "$agents_file" ] && ! grep -q 'IFSTORY_SKILL_START' "$agents_file"; then
    cat >> "$agents_file" <<BLOCK

<!-- IFSTORY_SKILL_START -->
## IF.story Skill
- Skill: \`ifstory\` (alias: \`if.story\`)
- Skill file: \`$skill_dir/SKILL.md\`
- Protocol: \`$skill_dir/references/IF.story.md\`
- Install source: \`$BASE_URL\`
- Output: AUTHENTIC + MEDIUM + CHRONICLE (paths discovered at runtime)
<!-- IFSTORY_SKILL_END -->
BLOCK
    echo "  Updated: $agents_file"
  fi

  echo "  Codex skill installed: $skill_dir"
}

# ── Install for Claude Code ────────────────────────────────────────────
install_claude() {
  local agent_dir="$CLAUDE_HOME/agents"
  local prompt_dir="$CLAUDE_HOME/ifstory"
  mkdir -p "$agent_dir" "$prompt_dir"
  cp "$ACTIVE_PAYLOAD_DIR/IF.story.md" "$prompt_dir/IF.story.md"

  cat > "$agent_dir/IF-story.md" <<AGENT
---
name: IF-story
description: Use when the user says \`if.story\`, \`ifstory\`, or asks to write session articles using the IF.story narrative workflow. Generate the full bundle of Authentic, Medium, and Chronicle outputs each time.
model: sonnet
---

You run the IF.story narrative workflow.

Source of truth:
- \`$prompt_dir/IF.story.md\`

Required behavior:
- Always generate all three outputs on each invocation:
  - \`AUTHENTIC\`
  - \`MEDIUM\`
  - \`CHRONICLE\`
- Read the bundled IF.story prompt before writing.
- Use the real session context, constraints, commands, file paths, and uncertainty.
- Do not replace the bundle with a single blended article.
- Discover the output location at runtime (see protocol Step 6).
- End with the manifest JSON required by the prompt.

Execution order:
1. Write \`AUTHENTIC\` first.
2. Derive \`MEDIUM\` from that record.
3. Write \`CHRONICLE\` last, using the actual session twist.

Guardrails:
- No fake positivity.
- No performed humility.
- If one form is weak, say so directly and still generate it.
- Keep the three-output bundle invariant even when adapting to a different repository layout.
AGENT

  echo "  Agent installed: $agent_dir/IF-story.md"
  echo "  Protocol installed: $prompt_dir/IF.story.md"

  local plugin_dir="$CLAUDE_HOME/plugins/marketplaces/local/plugins/ifstory"
  mkdir -p "$plugin_dir/.claude-plugin" "$plugin_dir/skills/if-story"

  cat > "$plugin_dir/.claude-plugin/plugin.json" <<'PJSON'
{
  "name": "ifstory",
  "description": "IF.story narrative workflow - generates AUTHENTIC + MEDIUM + CHRONICLE session articles",
  "version": "2.4.0",
  "author": { "name": "Danny Stocker / infrafabric" }
}
PJSON

  cat > "$plugin_dir/skills/if-story/SKILL.md" <<SKILLMD
---
name: if-story
description: Use when the user says "if.story", "ifstory", or "write your articles". Generates the full IF.story narrative bundle (AUTHENTIC + MEDIUM + CHRONICLE) for the current session.
version: 2.4.0
---

# IF.story Session Narrative Skill

Triggers the IF.story narrative workflow.

## When To Use

Activate when the user says: \`if.story\`, \`ifstory\`, or \`write your articles\`.

## What To Do

1. Read the full protocol at \`$prompt_dir/IF.story.md\`
2. Spawn the IF-story agent to execute the workflow
3. The agent generates **all three** outputs every time
4. Output paths are discovered at runtime (not hardcoded)

## Key Rules

- No fake positivity or performed humility
- Use real session context: file paths, commands, errors, uncertainty
- If one form is weak, say so directly and still generate it
- End with the manifest JSON required by the protocol
- Filename pattern: \`[TYPE]_[DATE]_[TITLE]_[MODEL].md\`

## Install source

\`$BASE_URL\`
SKILLMD

  echo "  Plugin skill installed: $plugin_dir"

  local mkt_dir="$CLAUDE_HOME/plugins/marketplaces/local"
  local mkt_file="$CLAUDE_HOME/plugins/known_marketplaces.json"
  local inst_file="$CLAUDE_HOME/plugins/installed_plugins.json"
  local settings="$CLAUDE_HOME/settings.json"
  local claude_file="$CLAUDE_HOME/CLAUDE.md"
  local ts
  ts="$(date -u +%Y-%m-%dT%H:%M:%S.000Z)"

  ensure_json_file "$mkt_file" '{}'
  ensure_json_file "$inst_file" '{"plugins":{}}'
  ensure_json_file "$settings" '{}'
  json_edit known_marketplace "$mkt_file" "$mkt_dir" "$ts"
  json_edit installed_plugin "$inst_file" "$ts"
  json_edit enabled_plugin "$settings"
  echo "  Updated plugin metadata under $CLAUDE_HOME/plugins"

  if [ ! -f "$claude_file" ]; then
    printf '# CLAUDE\n' > "$claude_file"
  fi
  if ! grep -q 'IFSTORY_AGENT_START' "$claude_file"; then
    cat >> "$claude_file" <<BLOCK

<!-- IFSTORY_AGENT_START -->
# IF.story Agent
- Local agent: \`$agent_dir/IF-story.md\`
- Protocol: \`$prompt_dir/IF.story.md\`
- Plugin skill: \`ifstory@local\`
- Install source: \`$BASE_URL\`
- Trigger words: \`if.story\`, \`ifstory\`, \`write your articles\`
- Output: AUTHENTIC + MEDIUM + CHRONICLE (paths discovered at runtime)
<!-- IFSTORY_AGENT_END -->
BLOCK
    echo "  Updated: $claude_file"
  fi
}

# ── Run ────────────────────────────────────────────────────────────────
echo "Installing IF.story skill v2.4..."
echo ""

$HAS_CODEX  && { echo "[Codex]"; install_codex; echo ""; }
$HAS_CLAUDE && { echo "[Claude Code]"; install_claude; echo ""; }

echo "Done. Restart your session to pick up the new skill."
echo ""
echo "Usage: say 'if.story' or 'ifstory' or 'write your articles'"
echo "Output: AUTHENTIC + MEDIUM + CHRONICLE (location discovered at runtime)"
