#!/usr/bin/python
# encoding: utf-8

import sys
import os
from os import path
import re

ROOT = path.realpath(path.dirname(sys.argv[0]) + '/../lib/ccnr3/drv')
if not path.exists(ROOT):
    sys.exit('Cannot found drivers.')
drivers = [i[0:-4].replace('_', '.') for i in os.listdir(ROOT) if '.lua' == i[-4:] and 'init' != i[0:-4]]

if 1 < len(sys.argv):
    ROOT = sys.argv[1]
else:
    ROOT = path.realpath(ROOT + '/../../../../db')
if not path.exists(ROOT):
    sys.exit('Invalid path of DB folder.')

novels = [i for i in os.listdir(ROOT) if path.isdir(ROOT + '/' + i)]
if 1 > len(novels):
    sys.exit('No novels found.')
print '> found %d novels:\n' % len(novels)

for novel in novels:
    prefix = ROOT + '/' + novel + '/'
    filepath = prefix + 'SOURCE'
    if path.isfile(filepath):
        pass
    elif path.isfile(filepath + '_'):
        filepath += '_'
    else:
        filepath = None
    source = None
    if filepath:
        with open(filepath) as fh:
            source = fh.read()
            fh.close()
    filepath = prefix + 'toc.xml'
    toc = None
    if path.isfile(filepath):
        with open(filepath) as fh:
            toc = fh.read()
            fh.close()
    title = novel
    if re.match(r'^[a-z]', novel):
        realtitle = '???'
        if toc:
            realtitle = re.match(r'<Title>!<\[CDATA\[(.*)\]\]></Title>', toc).group(1)
        title = '%s (%s)' % (novel, realtitle)
    print '* %s:' % title,
    missing = []
    if toc:
        for i in range(1, len(re.findall(r'<Chapter ', toc))):
            if not path.exists('%s%d.xml' % (prefix, i)):
                missing.append(str(i))
    elif source:
        found = False
        for driver in drivers:
            if driver in source:
                found = True
                break
        if not found:
            print 'driver missing'
            continue
        chapters = [int(i[0:-4]) for i in os.listdir(prefix) if '.xml' == i[-4:] and 'toc' != i[0:-4]]
        chapters.sort()
        if len(chapters) != chapters[-1]:
            missing = [str(i) for i in range(1, chapters[-1]) if i not in chapters]
    else:
        print 'broken'
        continue
    if 0 < len(missing):
        print '%s not found' % '/'.join(missing)
        continue
    print 'in progress' if source else 'complete'
