import textwrap


def _analysis_header_for_txt_file(analysis, as_comment=True):
    """

    Parameters
    ----------
    analysis
        Analysis instance
    as_comment
        boolean, if True, add '# ' in front of each line

    Returns
    -------
    str
    """

    subject = analysis.subject
    subject_creator = subject.creator
    subject_type_str = analysis.subject_type.model.title()
    headline = f"{subject_type_str}: {subject.name}"

    s = f'{headline}\n' +\
        '='*len(headline) + '\n' +\
        f'Creator: {subject_creator}\n' +\
        f'Further arguments of analysis function: {analysis.get_kwargs_display()}\n' +\
        f'Start time of analysis task: {analysis.start_time}\n' +\
        f'End time of analysis task: {analysis.end_time}\n' +\
        f'Duration of analysis task: {analysis.duration()}\n'
    if analysis.configuration is None:
        s += 'Versions of dependencies (like "SurfaceTopography") are unknown for this analysis.\n'
        s += 'Please recalculate in order to have version information here.\n'
    else:
        versions_used = analysis.configuration.versions.order_by('dependency__import_name')

        for version in versions_used:
            s += f"Version of '{version.dependency.import_name}': {version.number_as_string()}\n"
    s += '\n'

    if as_comment:
        s = textwrap.indent(s, '# ', predicate=lambda s: True)  # prepend to all lines, also empty

    return s