#!/usr/bin/env bash
# story: e39s05
# Decompose CONVENTIONS.md into specs/conventions-wiki/ OKF concept bundle
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)"
CONVENTIONS="$REPO_ROOT/CONVENTIONS.md"
CONVENTIONS_WIKI="$REPO_ROOT/specs/conventions-wiki"
CONVENTIONS_INDEX="$CONVENTIONS_WIKI/index.md"
SKILL_GRAPH="$REPO_ROOT/specs/skill-graph.json"

decompose_show_help() {
  cat <<EOF
Usage: $(basename "$0") [OPTION]

Decompose CONVENTIONS.md into specs/conventions-wiki/ OKF concept bundle.
Each major heading becomes a concept page with cross-references to enforcing skills.

Options:
  --help    Show this help and exit
EOF
}

if [ "$#" -eq 1 ] && [ "$1" = "--help" ]; then
  decompose_show_help
  exit 0
fi

if [ ! -f "$CONVENTIONS" ]; then
  echo "[ERROR] CONVENTIONS.md not found at $CONVENTIONS" >&2
  exit 1
fi

mkdir -p "$CONVENTIONS_WIKI"

# Generate index page
cat > "$CONVENTIONS_INDEX" << 'IDXEOF'
---
type: Index
title: Conventions Wiki
context: conventions
---

# Conventions Wiki — OKF Bundle

**Generated by:** scripts/decompose-conventions.sh (e39s05)

## Convention Sections

IDXEOF

# Parse CONVENTIONS.md headings into sections
$PYTHON -c "
import re, os, json

with open('$CONVENTIONS') as f:
    content = f.read()

# Split on markdown headings (## or ###)
sections = re.split(r'^(#{2,3})\s+(.+)$', content, flags=re.MULTILINE)

# Load skill graph for cross-references
graph_data = {}
if os.path.exists('$SKILL_GRAPH'):
    with open('$SKILL_GRAPH') as gf:
        graph_data = json.load(gf)

convention_skills = {}  # convention_name -> [skill_names]

# Build mapping from edges (skill -> convention)
for edge in graph_data.get('edges', []):
    src = edge.get('source', '')
    tgt = edge.get('target', '')
    rel = edge.get('relation', '')
    if rel == 'enforces' and tgt:
        # tgt is something like 'CONVENTIONS.md §Tests;'
        convention_name = tgt.replace('CONVENTIONS.md', '').replace('§', '').replace(';', '').strip()
        if convention_name:
            if convention_name not in convention_skills:
                convention_skills[convention_name] = []
            convention_skills[convention_name].append(src)

# Process sections
current_level = ''
current_title = ''
current_body = []
section_count = 0

for part in sections:
    if part in ('##', '###'):
        current_level = part
    elif current_level and (current_title == ''):
        current_title = part.strip()
    elif current_level and current_title:
        current_body.append(part)
    elif current_level and current_title and not part.startswith('#'):
        current_body.append(part)

# Actually let me rebuild this properly
lines = content.split('\n')
i = 0
sections_data = []
current = None

while i < len(lines):
    line = lines[i]
    m = re.match(r'^(###?)\s+(.+)$', line)
    if m:
        if current:
            sections_data.append(current)
        current = {
            'level': len(m.group(1)),
            'title': m.group(2).strip(),
            'body': []
        }
    elif current:
        current['body'].append(line)
    i += 1

if current:
    sections_data.append(current)

with open('$CONVENTIONS_INDEX', 'a') as idx:
    for sec in sections_data:
        slug = re.sub(r'[^a-z0-9]+', '-', sec['title'].lower()).strip('-')
        sec_file = os.path.join('$CONVENTIONS_WIKI', f'{slug}.md')

        # Check for enforcing skills
        enforcing = convention_skills.get(sec['title'], [])

        body_text = '\n'.join(sec['body']).strip()

        with open(sec_file, 'w') as sf:
            sf.write(f'---\ntype: Convention\ntitle: {sec[\"title\"]}\ncontext: conventions\n')
            if enforcing:
                sf.write(f'enforced_by:\n')
                for sk in enforcing:
                    sf.write(f'  - {sk}\n')
            sf.write(f'---\n\n# {sec[\"title\"]}\n\n')
            sf.write(f'{body_text}\n\n---\n*Auto-generated by scripts/decompose-conventions.sh (e39s05)*\n')

        idx.write(f'- [{sec[\"title\"]}]({slug}.md)\\n')
        section_count += 1

print(f'OK: {section_count} convention sections written to specs/conventions-wiki/')
"
