#!/usr/bin/env bash
# story: e39s06
# Decompose CLAUDE.md into specs/agent-guide/ for progressive disclosure
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)"
CLAUDE_MD="$REPO_ROOT/CLAUDE.md"
AGENT_GUIDE="$REPO_ROOT/specs/agent-guide"

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

Decompose CLAUDE.md into specs/agent-guide/ OKF concept pages.
Each section becomes a Guide concept with thin pointers.

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

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

if [ ! -f "$CLAUDE_MD" ]; then
  echo "[WARN] CLAUDE.md not found — trying GEMINI.md" >&2
  CLAUDE_MD="$REPO_ROOT/GEMINI.md"
  if [ ! -f "$CLAUDE_MD" ]; then
    echo "[ERROR] Neither CLAUDE.md nor GEMINI.md found" >&2
    exit 1
  fi
fi

mkdir -p "$AGENT_GUIDE"

$PYTHON -c "
import re, os

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

lines = content.split('\n')
sections = []
current_title = ''
current_body = []

for line in lines:
    m = re.match(r'^(#{2,3})\s+(.+)$', line)
    if m:
        if current_title:
            sections.append((current_title, '\n'.join(current_body)))
        current_title = m.group(2).strip()
        current_body = []
    elif current_title:
        current_body.append(line)

if current_title:
    sections.append((current_title, '\n'.join(current_body)))

guide_dir = '$AGENT_GUIDE'

with open(os.path.join(guide_dir, 'index.md'), 'w') as idx:
    idx.write('---\ntype: Index\ntitle: Agent Guide\ncontext: guide\n---\n\n')
    idx.write('# Agent Guide — OKF Bundle\n\n')
    idx.write(f'**Generated by:** scripts/generate-agent-guide.sh (e39s06)\n')
    idx.write(f'**Source:** CLAUDE.md\n\n')
    idx.write('## Guide Sections\n\n')

    for title, body in sections:
        slug = re.sub(r'[^a-z0-9]+', '-', title.lower()).strip('-')
        sec_file = os.path.join(guide_dir, f'{slug}.md')

        with open(sec_file, 'w') as sf:
            sf.write(f'---\ntype: Guide\ntitle: {title}\ncontext: guide\n')
            sf.write(f'source: CLAUDE.md#{slug}\n---\n\n')
            sf.write(f'# {title}\n\n')
            # Thin pointer — first 200 chars
            preview = body.strip()[:200]
            sf.write(f'{preview}\n\n')
            sf.write(f'> Full content: $CLAUDE_MD section \"{title}\"\n')
            sf.write('---\n*Auto-generated by scripts/generate-agent-guide.sh*\n')

        idx.write(f'- [{title}]({slug}.md)\n')

print(f'OK: {len(sections)} guide sections written to specs/agent-guide/')
"
