import argparse
import logging
import os
import sys
from falcon_unzip import io

LOG = logging.getLogger()

def run(gathered_fn, gathered_key, output_fn):
    gathered_dir = os.path.dirname(gathered_fn)
    out_dir = os.path.dirname(output_fn)

    io.rm(output_fn)

    io.rm(output_fn)
    io.touch(output_fn)
    gathered = io.deserialize(gathered_fn)
    for job_output in gathered:
        fn = job_output[gathered_key]
        if not os.path.isabs(fn):
            fn = os.path.relpath(os.path.join(gathered_dir, fn), out_dir)

        io.syscall('sort -k11,11 -k1,1n < {fn} >> {output_fn}'.format(fn=fn, output_fn=output_fn))

class HelpF(argparse.RawTextHelpFormatter, argparse.ArgumentDefaultsHelpFormatter):
    pass

def parse_args(argv):
    description = 'Concatenate output files.'
    epilog = ''
    parser = argparse.ArgumentParser(
        description=description,
        epilog=epilog,
        formatter_class=HelpF,
    )
    parser.add_argument(
        '--gathered-fn',
        type=str,
        help='Input: dict of ctg-> dict of "fn"->rid_to_phase filename',
        required=True,
    )
    parser.add_argument(
        '--gathered-key',
        type=str,
        default='coords',
        help='Key from the gathered-fn dict to collect.',
    )
    parser.add_argument(
        '--output-fn',
        type=str,
        help='Output: Concatenated output file.',
        required=True,
    )
    args = parser.parse_args(argv[1:])
    return args

def main(argv=sys.argv):
    args = parse_args(argv)
    logging.basicConfig(level=logging.INFO)
    run(**vars(args))

if __name__ == '__main__':  # pragma: no cover
    main()
