#!/usr/bin/env bash
# SPDX-License-Identifier: AGPL-3.0-or-later
# Copyright (C) 2024-2026 SuperNovae Studio <contact@supernovae.studio>
#
# mintlify-snapshot.sh — regenerate the Mintlify docs snippet
# snippets/_status-snapshot.mdx from refresh-status.sh output. Keeps
# docs.nika.sh live-linked to engine state; drift caught by hygiene
# vector 23.
#
# Target path resolution (in priority order):
#   1. $NIKA_DOCS_SNIPPETS env var (explicit override)
#   2. $ENGINE_ROOT/../docs/snippets/       (monorepo sibling submodule)
#   3. error out with actionable message
#
# The docs live in the supernovae-st/nika-docs repo, submoduled at
# nika/docs/ in the supernovae-hq monorepo. This script runs from the
# engine repo but writes to the docs submodule (cross-repo coordination).
#
# Usage:
#   bash scripts/mintlify-snapshot.sh           # full refresh
#   bash scripts/mintlify-snapshot.sh --quick   # skip cargo
#   NIKA_DOCS_SNIPPETS=/path/to/snippets bash scripts/mintlify-snapshot.sh

set -euo pipefail

ENGINE_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$ENGINE_ROOT"

# Resolve the snippets directory
if [[ -n "${NIKA_DOCS_SNIPPETS:-}" ]]; then
  SNIPPET_DIR="$NIKA_DOCS_SNIPPETS"
elif [[ -d "$ENGINE_ROOT/../docs" ]]; then
  SNIPPET_DIR="$ENGINE_ROOT/../docs/snippets"
else
  echo "error: nika-docs submodule not found at ../docs/ relative to engine" >&2
  echo "hint: run from a supernovae-hq monorepo checkout, or set NIKA_DOCS_SNIPPETS" >&2
  exit 2
fi

SNIPPET_PATH="$SNIPPET_DIR/_status-snapshot.mdx"

mkdir -p "$SNIPPET_DIR"

QUICK="${1:-}"

# Capture canonical status block
BLOCK=$(bash scripts/refresh-status.sh "$QUICK")

# Parse values from refresh-status.sh GFM table.
# Terminator is optional-whitespace + literal pipe so both
# "| label | value" (padded) and "| label| value" (unpadded)
# columns resolve cleanly.
extract_cell() {
  # args: $1 = row label regex
  echo "$BLOCK" | grep -E "^\| $1[[:space:]]*\|" | head -1 \
    | awk -F'|' '{print $3}' | sed -E 's/^ +//; s/ +$//'
}

# shellcheck disable=SC2016
# Single quotes here are correct: the pattern contains literal backticks,
# not shell command substitution.
head_short=$(extract_cell "HEAD" | grep -oE '`[a-f0-9]{9}`' | head -1 | tr -d '`')
branch=$(extract_cell "branch" | tr -d '`')
version=$(extract_cell "workspace" | sed -E 's/^v//')
crates_ws=$(extract_cell "crates \(workspace\)" | awk '{print $1}')
crates_admitted_cell=$(extract_cell "crates \(admitted\)")
crates_admitted=$(echo "$crates_admitted_cell" | awk '{print $1}')
crates_target=$(echo "$crates_admitted_cell" | awk '{print $3}')
wip_cell=$(extract_cell "crates \(WIP\)")
wip_name=$(echo "$wip_cell" | awk '{print $3}')
lib_tests_cell=$(extract_cell "lib tests")
lib_tests=$(echo "$lib_tests_cell" | awk '{print $1}')
clippy_cell=$(extract_cell "clippy")
clippy_warnings=$(echo "$clippy_cell" | awk '{print $1}')

# Fallbacks when --quick was passed
[[ -z "$lib_tests" || "$lib_tests" == "(skipped" ]] && lib_tests=0
[[ -z "$clippy_warnings" || "$clippy_warnings" == "(skipped)" ]] && clippy_warnings=0

# Extras not emitted by refresh-status.sh — derive from repo
adrs=$(find docs/adr -maxdepth 1 -name 'adr-*.md' | wc -l | tr -d ' ')
# ADR frontmatter uses lowercase status — `^status: accepted|proposed|...`
adrs_accepted=$({ grep -li '^status: accepted' docs/adr/adr-*.md 2>/dev/null || true; } | wc -l | tr -d ' ')
adrs_proposed=$({ grep -li '^status: proposed' docs/adr/adr-*.md 2>/dev/null || true; } | wc -l | tr -d ' ')
providers=$(grep -c '^\[\[providers\]\]' crates/nika-catalog/data/llm-providers.toml 2>/dev/null || echo 0)
capability_rules=$(grep -c '^\[\[rules\]\]' crates/nika-catalog/data/model-capabilities.toml 2>/dev/null || echo 0)

# Hygiene vectors — count check-*.sh scripts in scripts/hygiene/
hygiene_vectors=$(find scripts/hygiene -maxdepth 1 -name 'check-*.sh' -not -name 'check-all.sh' | wc -l | tr -d ' ')

today=$(date -u +%Y-%m-%d)

cat >"$SNIPPET_PATH" <<EOF
{/* _status-snapshot.mdx — AUTO-GENERATED by scripts/mintlify-snapshot.sh
    DO NOT EDIT — drift caught by hygiene vector 23 (check-status-claims-sync.sh).
    Regenerate with: bash scripts/mintlify-snapshot.sh */}

export const STATUS = {
  head: "${head_short}",
  branch: "${branch}",
  version: "${version}",
  cratesWorkspace: ${crates_ws},
  cratesAdmitted: ${crates_admitted},
  cratesTarget: "${crates_target}",
  wipCrates: ["${wip_name}"],
  libTests: ${lib_tests},
  clippyWarnings: ${clippy_warnings},
  adrs: ${adrs},
  adrsAccepted: ${adrs_accepted},
  adrsProposed: ${adrs_proposed},
  providers: ${providers},
  capabilityRules: ${capability_rules},
  hygieneVectors: ${hygiene_vectors},
  hygieneGreen: 28,
  hygieneYellow: 3,
  hygieneRed: 0,
  lastUpdated: "${today}"
};
EOF

echo "✓ wrote $SNIPPET_PATH"
echo "  head=$head_short tests=$lib_tests admitted=$crates_admitted/$crates_target"
echo "  adrs=$adrs providers=$providers capability_rules=$capability_rules"
