#!/usr/bin/env bash
# story: e39s04
# okf-post-sync.sh — Post-processing pipeline for OKF skills-wiki generation.
# Called by sync-skills.sh --okf after concept files are rendered.
# Steps: cross-references from skill-graph.json → index.md → validate-okf.sh
set -euo pipefail
source "$(dirname "${BASH_SOURCE[0]}")/lib/python-env.sh"
source "$(dirname "${BASH_SOURCE[0]}")/lib/skill-common.sh"
resolve_repo_root

GRAPH_JSON="$REPO_ROOT/specs/skill-graph.json"
OKF_WIKI_SKILLS="$REPO_ROOT/specs/skills-wiki/skills"
OKF_WIKI_DIR="$REPO_ROOT/specs/skills-wiki"
OKF_INDEX="$OKF_WIKI_DIR/index.md"

# ── Step 1: Run build-skill-graph.sh for cross-references ──────────
echo ""
echo "--- OKF post-sync ---"
echo "Step 1: Cross-references from skill graph..."

if [[ -x "$REPO_ROOT/scripts/build-skill-graph.sh" ]]; then
  bash "$REPO_ROOT/scripts/build-skill-graph.sh" --json || {
    echo "  WARNING: build-skill-graph.sh --json failed; cross-references will be fallback" >&2
  }
else
  echo "  WARNING: build-skill-graph.sh not found" >&2
fi

# ── Step 2: Add cross-references from skill-graph.json ─────────────
echo "Step 2: Adding cross-references to OKF concepts..."

if [[ -f "$GRAPH_JSON" ]] && command -v $PYTHON &>/dev/null; then
  $PYTHON "$REPO_ROOT/scripts/okf-add-references.py" "$GRAPH_JSON" "$OKF_WIKI_SKILLS"
else
  echo "  Adding fallback references..."
  for f in "$OKF_WIKI_SKILLS"/*.md; do
    [[ -f "$f" ]] || continue
    $PYTHON -c "
import re
c = open('$f').read()
c = re.sub(r'references:\s*\[\]', 'references:\n  - concept: skills-wiki\n    type: belongs_to', c)
open('$f','w').write(c)
" 2>/dev/null || true
  done
fi

# ── Step 3: Generate index.md with progressive disclosure ──────────
echo "Step 3: Generating index.md..."

$PYTHON - "$OKF_WIKI_SKILLS" "$OKF_INDEX" <<'PYEOF'
import re, sys
from pathlib import Path
from collections import defaultdict

wiki_skills = Path(sys.argv[1])
index_path = Path(sys.argv[2])

concepts = []
for f in sorted(wiki_skills.glob("*.md")):
    content = f.read_text()
    fm_match = re.search(r'^---\n(.*?)\n---', content, re.DOTALL)
    if not fm_match:
        continue
    fm_text = fm_match.group(1)
    name = title = phase = model = effort = description = ""
    for line in fm_text.split('\n'):
        line = line.strip()
        if line.startswith('name:'): name = line.split(':', 1)[1].strip()
        elif line.startswith('title:'): title = line.split(':', 1)[1].strip().strip('"')
        elif line.startswith('phase:'): phase = line.split(':', 1)[1].strip()
        elif line.startswith('model:'): model = line.split(':', 1)[1].strip()
        elif line.startswith('effort:'): effort = line.split(':', 1)[1].strip()
        elif line.startswith('description:'): description = line.split(':', 1)[1].strip().strip('"')
    if not name:
        continue
    concepts.append({
        "name": name,
        "title": title or name.replace('-', ' ').title(),
        "phase": phase or "utility",
        "model": model,
        "effort": effort,
        "description": (description[:120] + "...") if len(description) > 120 else description,
    })

phases = defaultdict(list)
for c in concepts:
    phases[c["phase"]].append(c)

total = len(concepts)
cp = phases.get("critical-path", [])
util = phases.get("utility", [])

with open(index_path, "w") as out:
    out.write(f"""---
okf_kind: concept
type: Index
id: skills-wiki
title: "BigPowers Skills Wiki"
category: skills
description: "Progressive-disclosure index of {total} bigpowers skills ({len(cp)} critical-path, {len(util)} utility) — auto-generated by sync-skills.sh --okf (e39s04)."
references:
  - concept: bigpowers
    type: belongs_to
---

# BigPowers Skills Wiki

**{total} skills** ({len(cp)} critical-path, {len(util)} utility)

> Auto-generated by sync-skills.sh --okf (e39s04). Source of truth: skills/*/SKILL.md files.

## Critical-Path Skills ({len(cp)})

These skills form the bigpowers core development loop.

| Skill | Model | Effort | Description |
|-------|-------|--------|-------------|
""")
    for c in cp:
        out.write(f"| [{c['title']}](skills/{c['name']}.md) | {c['model']} | {c['effort']} | {c['description']} |\n")

    out.write(f"""
## Utility Skills ({len(util)})

Supporting skills for specialised workflows.

| Skill | Model | Effort | Description |
|-------|-------|--------|-------------|
""")
    for c in util:
        out.write(f"| [{c['title']}](skills/{c['name']}.md) | {c['model']} | {c['effort']} | {c['description']} |\n")

    out.write(f"""
## Quick Reference

- **Total skills:** {total}
- **Critical-path:** {len(cp)}
- **Utility:** {len(util)}
- **Format:** OKF concept bundles (okf_kind: concept)
- **Validation:** `bash scripts/validate-okf.sh --dir specs/skills-wiki/skills`
""")

print(f"  index.md written: {total} skills ({len(cp)} critical-path, {len(util)} utility)")
PYEOF

# ── Step 4: Validate OKF conformance ───────────────────────────────
echo "Step 4: Validating OKF conformance..."

VALIDATE_SCRIPT="$REPO_ROOT/scripts/validate-okf.sh"
if [[ -x "$VALIDATE_SCRIPT" ]]; then
  if bash "$VALIDATE_SCRIPT" --dir "$OKF_WIKI_SKILLS" 2>&1; then
    echo "  OKF validation: PASSED"
  else
    OKF_EXIT=$?
    echo "  OKF validation: exit code $OKF_EXIT (non-zero — see output above)" >&2
  fi
else
  echo "  WARNING: validate-okf.sh not found; skipping validation" >&2
fi

OKF_COUNT=$(find "$OKF_WIKI_SKILLS" -name "*.md" 2>/dev/null | wc -l | tr -d ' ')
echo ""
echo "okf-post-sync: $OKF_COUNT OKF concepts generated"
echo "  → specs/skills-wiki/skills/ ($OKF_COUNT .md files)"
echo "  → specs/skills-wiki/index.md (progressive-disclosure index)"
