rule create_info:
  input:
    'summary.txt',
    all_faa='seqs/all.faa'
  output:
    'job_info.txt'
  message:
    "writing job_info ..."
  version:
    "0.1"
  run:
    import git
    from git import InvalidGitRepositoryError

    # not in input because this file is produced conditionally
    missing_taxa_faa='seqs/missing_taxa.faa'

    # get git commit hash
    try:
        repo = git.Repo(workflow.basedir)
        sha = repo.head.object.hexsha
    except InvalidGitRepositoryError:
        sha = "not a git repository"

    # read start time from persistent storage
    START_TIME = storage.fetch("START_TIME")

    out = []
    out.append("PROPHANE JOB INFORMATION")
    out.append('')
    out.append('a. general information')
    out.append('   job name: ' + config['general']['job_name'])
    out.append('   job comment: ' + config['general']['job_comment'])
    out.append('   start time: ' + START_TIME)
    out.append('   end time: ' + get_timestamp())
    out.append('')
    out.append('b. program versions')
    out.append('   prophane: ' + PROPHANE_VERSION)
    out.append('   git commit sha: {}'.format(sha))
    out.append('')
    out.append('c. input')
    if 'report' in config['input']:
        out.append('   protein report (Scaffold): ' + os.path.basename(config['input']['report']))
        out.append('   report style: ' + os.path.basename(config['input']['report_style']))
    elif 'pdxml' in config['input']:
        out.append('   protein xml (Proteome Discoverer): ' + os.path.basename(config['input']['pdxml']))
        out.append('   psms txt (Proteome Discoverer): ' + os.path.basename(config['input']['pdpsms']))
        out.append('   xml/psms style: ' + os.path.basename(config['input']['report_style']))
    if not config['input']['fastas']:
        out.append('   sequence data: None')
    else:
        out.append('   sequence data:')
        for fname in config['input']['fastas']:
            out.append('      - ' + os.path.basename(fname))
    if not config['input']['taxmaps']:
        out.append('   taxonomic data: None')
    else:
        out.append('   taxonomic data:')
        for fname in config['input']['taxmaps']:
            out.append('      - ' + os.path.basename(fname))
    out.append('')
    out.append('d. sample groups')
    if 'sample_groups' not in config:
        out.append('   not defined')
    else:
        for g in sorted(config['sample_groups'].keys()):
            out.append(f'   {g}')
            for s in config['sample_groups'][g]:
                out.append(f'      - {s}')
    out.append('')
    out.append('e. tasks')
    n = -1
    for task in config['tasks']:
        n += 1
        out.append(f'   task: {n}')
        out.append(f"   task comment: {task['shortname']}")
        out.append(f"   algorithm: {task['prog']}")
        if task['type'] == 'taxonomic':
            out.append(f'   query: sequences without taxonomic classification ({missing_taxa_faa})')
        elif task['type'] == 'functional':
            out.append(f"   query: all sequences ({input['all_faa']})")
        else:
            raise ValueError(f"Type of task {n} is only allowed to be 'functional' or 'taxonomic' but is {task['type']}")
        if task['prog'] != 'acc2annot_mapper':
            db_obj = get_db_object_for_task(task)
            out.append(f'   database: {db_obj.get_name()}')
            out.append(f'   database version: {db_obj.get_version()}')
            out.append(f'   database comment: {db_obj.get_comment()}')
            out.append(f'   database scope: {db_obj.get_scope()}')
        out.append('   parameter:')
        if 'params' in task:
            for param, val in task['params'].items():
                out.append('      - ' + param + " " + str(val))
        for param, val in task.items():
            if param in ['prog', 'shortname', 'query', 'db', 'params']:
                continue
            out.append(f"      - {param}  {val}")
        out.append('')

    out.append('f. lca')
    out.append('   lca method: ' + config['lca']['method'])
    out.append('   lca threshold: ' + str(config['lca']['threshold']))

    with open(output[0], "w") as handle:
        handle.write("\n".join(out))
