import io
from glob import glob

from .. import click
from ._utils import call, DEVNULL


@click.command()
def main():
    """
    Compile all requirements files (*.in).
    """
    compile_all_requirements()


def compile_all_requirements():
    option_lines = list(get_option_lines('requirements.in'))
    src_reqs = ['requirements.in'] + sorted(glob('requirements-*.in'))
    for src_file in src_reqs:
        txt_file = src_file.replace('.in', '.txt')
        print('*** Compiling {} to {}'.format(src_file, txt_file))
        call('prequ compile --no-index --no-header --no-annotate {r}',
             r=src_file, stdout=DEVNULL)
        postprocess_requirement_file(txt_file, option_lines)


def get_option_lines(filename):
    ignored = (
        '-r', '--requirement',
        '-e', '--editable',
        '-c', '--constraint',
    )
    with open(filename, 'rt', encoding='utf-8') as fp:
        for line in fp:
            cleaned = line.strip()
            if cleaned.startswith('-') and not cleaned.startswith(ignored):
                yield cleaned


def postprocess_requirement_file(filename, option_lines):
    header = [
        '# This file is autogenerated by Prequ.  To update, run:',
        '#',
        '#   prequ update',
        '',
    ]
    with io.open(filename, 'r+t', encoding='utf-8') as fp:
        req_lines = [line.strip() for line in fp.readlines()]
        fp.seek(0)
        fp.truncate()
        for line in header + option_lines + [''] + req_lines:
            fp.write(line + '\n')
