#!/usr/bin/env python3
import os
import re
from markdown import markdown

DOCS = "/Users/brennannovak/MailPileCode/doc/"
if not os.path.exists(DOCS):
    DOCS = '../../Code/doc/'
if not os.path.exists(DOCS):
    DOCS = '../Mailpile/doc/'
if not os.path.exists(DOCS):
    DOCS = '../../Mailpile/doc/'
if not os.path.exists(DOCS):
    raise ValueError('Could not find wiki')

# First we parse the wiki TOC for sub-pages...
FAQS = []
shorts = []
wiki_toc = open(os.path.join(DOCS, 'Frequently-Asked-Questions.md')).read()
tocl_re = re.compile(r'^\s*\*\s+\[([^\]]+)\]\(([^\)]+)\)\s*$')
for line in wiki_toc.splitlines():
    m = re.match(tocl_re, line)
    if m:
        short = re.sub(r'[^a-zA-Z0-9]', '', m.group(1).lower())
        for i in range(3, 20):
            if short[:i] not in shorts:
                short = short[:i]
                shorts.append(short)
                break
        FAQS.append((short, m.group(1), '%s.md' % m.group(2)))


# Then, parse each sub-page, generating a TOC and actual content.
toc = []
answers = []
for section, title, fn in FAQS:
    data = open(os.path.join(DOCS, fn)).read()

    # Initialize the table-of-contents for this section
    toc.append('<li class="section"><a href="#%s">%s</a><ul>' % (section, title))

    # Markdown helpfully puts each paragraph/heading on a new line, so we can
    # just iterate through the lines and edit/insert things we need.
    marked = []
    q_count = 1
    for line in markdown(data).splitlines():
        if '<h3>' in line:
            question_toc = line.replace('<h3>', '').replace('</h3>', '')            
            qid = '%s-%s' % (section, q_count)
            toc.append('<li class="section-%s">'
                       '<a class="toc-go" href="#%s">%s</a></li>'
                       % (section, qid, question_toc))

            if q_count > 1:
                marked.append('</li>')
                
            # 
            question = line.replace('<h3>', '<h3 class="faq-title">')
            marked.append('<li class="faq-item"><a class="anchor" id="%s"></a>'
                          ' %s <span class="faq-section">%s</span>'
                          % (qid, question, section))
            q_count += 1
        else:
            marked.append(line)

    if q_count > 1:
        marked.append('</li>')

    toc.append('</ul></li>')
    answers.extend(['<li class="faq-section-title">'
                    '<a class="anchor" id="%s"></a>'
                    '<h2>%s</h2></li>' % (section, title)] + marked)


# Finally, render as something the website builder understands
print("""\
Subject: Frequently Asked Questions
Format: html
Type: full
Redirect: /blog/
Comment: - DO NOT EDIT - This file is autogenerated by index.md.py

""")
if False:
  print( '<div id="faq">')
  print(  open('top-snippet.html').read())
  print(  '<div id="toc"><ul>')
  print(    '\n'.join(toc))
  print(   '</ul></div><ul class="list">')
  print(     '\n'.join(answers))
  print(   '</ul>')
  print(   '<hr>')
  print( '</div>')
else:
  print('<br><br><br><br>')
  print('<h3><i><center>')
  print(  'Temporarily unavailable: Check out the blog!')
  print('</center></i></h3>')
  print('<br><br><br><br>')

