"""
Generates the `mhelper` readme from the module documentation. 
"""
import os.path
import sys


directory = "./mhelper"
readme = "./readme.rst"

if not os.path.isdir( directory ):
    print( "1. Wrong place.", file = sys.stderr )
    exit( 1 )

if not os.path.isfile( readme ):
    print( "2. Wrong place.", file = sys.stderr )
    exit( 2 )

files = sorted( x for x in list( os.path.join( directory, x ) for x in os.listdir( directory ) ) )

c = []

for file in files:
    fn = os.path.splitext( os.path.basename( file ) )[0]
    
    if not os.path.isfile( file ):
        file = os.path.join( file, "__init__.py" )
        
        if not os.path.isfile( file ):
            continue
    
    if not file.endswith( ".py" ):
        continue
    
    if fn.startswith( "_" ):
        continue
    
    f = []
    
    with open( file ) as fil:
        bgn = 0
        
        l1 = next( fil ).strip()
        
        if l1 != '"""':
            continue
        
        f.append( "" )
        f.append( "" )
        f.append( fn )
        f.append( "-" * len( fn ) )
        
        for line in fil:
            line = line.rstrip()
            lin = line.lstrip()
            
            if lin == '"""':
                break
            
            if "deprecated" in lin.lower():
                f.clear()
                break
            
            f.append( line )
        
        c.extend( f )

d = []

with open( readme ) as fil:
    for line in fil:
        line = line.rstrip()
        lin = line.lstrip()
        d.append( line )
        
        if lin == ".. contents::":
            break

d.append( "" )
d.append( ".. **** autogenerated content follows ****" )
d.extend( c )

with open( readme, "w" ) as fil:
    for f in d:
        fil.write( f )
        fil.write( "\n" )

print( "0. Ok", file = sys.stderr )
exit( 0 )
