#!/usr/bin/env bash
# story: e39s01
# Consume e32 build_skill_graph MCP output (bigpowers-mcp/graph.jsonl) and emit:
#   - specs/skill-graph.json    — machine-readable dependency graph
#   - specs/skills-wiki/        — OKF wiki with per-skill pages
set -euo pipefail
source "$(dirname "${BASH_SOURCE[0]}")/lib/python-env.sh"

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
GRAPH_JSONL="$REPO_ROOT/bigpowers-mcp/graph.jsonl"
SKILL_GRAPH_JSON="$REPO_ROOT/specs/skill-graph.json"
SKILLS_WIKI="$REPO_ROOT/specs/skills-wiki/skills"

# --- Error handling ---
missing_graph() {
  echo "[ERROR] MCP graph not found at: $GRAPH_JSONL" >&2
  echo "[ERROR] Run 'cd bigpowers-mcp && npm start' or e32s02 MCP tool first" >&2
  exit 1
}

if [ ! -f "$GRAPH_JSONL" ]; then
  missing_graph
fi

# --- Read graph.jsonl into temporary JSON ---
TMP_NODES=$(mktemp)
TMP_EDGES=$(mktemp)
TMP_ALL=$(mktemp)

$PYTHON -c "
import json, sys

nodes = {}
edges = []

with open('$GRAPH_JSONL') as f:
    for line in f:
        obj = json.loads(line)
        if obj.get('type') == 'entity':
            nodes[obj['name']] = {
                'id': obj['name'],
                'type': obj.get('entityType', 'Skill'),
                'observations': obj.get('observations', [])
            }
        elif obj.get('type') == 'relation':
            edges.append({
                'source': obj.get('from', ''),
                'target': obj.get('to', ''),
                'relation': obj.get('relationType', 'references'),
                'provenance': obj.get('provenance', '')
            })

# Emit node list
print(json.dumps(list(nodes.values()), indent=2))
" > "$TMP_NODES"

$PYTHON -c "
import json
# re-read edges into a separate file
edges = []
with open('$GRAPH_JSONL') as f:
    for line in f:
        obj = json.loads(line)
        if obj.get('type') == 'relation':
            edges.append({
                'source': obj.get('from', ''),
                'target': obj.get('to', ''),
                'relation': obj.get('relationType', 'references'),
                'provenance': obj.get('provenance', '')
            })
print(json.dumps(edges, indent=2))
" > "$TMP_EDGES"

# --- Write skill-graph.json ---
$PYTHON -c "
import json

with open('$TMP_NODES') as f:
    nodes = json.load(f)
with open('$TMP_EDGES') as f:
    edges = json.load(f)

graph = {
    'meta': {
        'source': 'bigpowers-mcp/graph.jsonl',
        'generated_by': 'scripts/build-skill-graph.sh',
        'node_count': len(nodes),
        'edge_count': len(edges)
    },
    'nodes': nodes,
    'edges': edges
}

with open('$SKILL_GRAPH_JSON', 'w') as f:
    json.dump(graph, f, indent=2)

print(f'OK: {len(nodes)} nodes, {len(edges)} edges written to specs/skill-graph.json')
"

# --- Emit specs/skills-wiki/ OKF bundle ---
WIKI_INDEX="$REPO_ROOT/specs/skills-wiki/index.md"
mkdir -p "$SKILLS_WIKI"

# Generate index page
cat > "$WIKI_INDEX" << WEOF
# Skills Wiki — OKF Bundle

---
type: Index
title: Skills Wiki
context: benchmark
---

**Generated by:** scripts/build-skill-graph.sh  
**Source:** bigpowers-mcp/graph.jsonl

## Skill Index

WEOF

# Generate one .md per skill
$PYTHON -c "
import json, os

# Re-read nodes
with open('$TMP_NODES') as f:
    nodes = json.load(f)

skills_dir = '$SKILLS_WIKI'
index_path = '$WIKI_INDEX'

# Sort by phase then name
nodes.sort(key=lambda n: (n.get('type', ''), n['id']))

with open(index_path, 'a') as idx:
    for node in nodes:
        name = node['id']
        ntype = node.get('type', 'Skill')
        obs = node.get('observations', [])

        slug = name  # already kebab-case

        # Extract key fields from observations
        model = ''
        effort = ''
        desc = ''
        for o in obs:
            if o.startswith('model:'):
                model = o.replace('model:', '').strip()
            elif o.startswith('effort:'):
                effort = o.replace('effort:', '').strip()
            elif o.startswith('description:'):
                desc = o.replace('description:', '').strip()

        # Write skill page
        page = f'''# {name}

**Type:** {ntype}  
**Model:** {model or 'default'}  
**Effort:** {effort or 'standard'}

{desc}

---

*Auto-generated by scripts/build-skill-graph.sh*
'''
        with open(os.path.join(skills_dir, f'{slug}.md'), 'w') as pf:
            pf.write(page)

        # Add to index
        idx.write(f'- [{name}](skills/{slug}.md) — {desc[:80] if desc else \"\"}\\n')

print(f'OK: {len(nodes)} skill pages written to specs/skills-wiki/skills/')
"

# Cleanup
rm -f "$TMP_NODES" "$TMP_EDGES" "$TMP_ALL"

echo "Done."
