# -*- coding: utf-8 -*-

import platform
import sys
import getopt
import pykakasi

try:
    from importlib import metadata as importlib_metadata  # noqa
except ImportError:
    import importlib_metadata


def show_version():
    dist = importlib_metadata.distribution('pykakasi')
    py_version = platform.python_version()
    py_impl = platform.python_implementation()
    py_build = platform.python_compiler()
    print("pykakasi: version {} on Python {} [{} {}]".format(dist.version, py_version, py_impl, py_build))


def usage():
    print("Python implementation of kakasi\n")
    print("{}".format(pykakasi.__copyright__))
    print("URL: {}".format(pykakasi.__url__))


def do_wakati(mode, infile, outfile):
    kakasi = pykakasi.wakati()
    do_it(kakasi, mode, infile, outfile)

def do_kakasi(mode, infile, outfile):
    kakasi = pykakasi.kakasi()
    do_it(kakasi, mode, infile, outfile)

def do_it(kakasi, mode, infile, outfile):
    try:
        for k,v in mode.iteritems():
            kakasi.setMode(k,v)
    except:
        for k,v in mode.items():
            kakasi.setMode(k,v)
    converter  = kakasi.getConverter()
    if infile:
        infp = open(infile,'r')
    else:
        infp = sys.stdin
    if outfile:
        outfp = open(outfile,'w')
    else:
        outfp = sys.stdout
    for line in infp:
        outfp.write(converter.do(line))

def main():
    outfile = None
    infile  = None
    wakati = False
    mode = {}
    values = ("J","H","K","E","a")
    romanvals = {"h":"Hepburn", "k":"Kunrei", "p":"Passport"}

    try:
        opts, args = getopt.getopt(sys.argv[1:],
            "hvI:O:wsS:J:H:K:E:a:r:fC",
            ["help","version","input=","output=","wakati","space","separator="])
    except getopt.GetoptError as err:
        print (err)
        usage()
        sys.exit(2)

    for o, a in opts:
        if o in ["-v","--version"]:
            show_version()
            sys.exit()
        elif o in ("-h", "--help"):
            show_version()
            usage()
            sys.exit()
        elif o in ("-I", "--input"):
            infile = a
        elif o in ("-O", "--output"):
            outfile = a
        elif o in ("-w", "--wakati"):
            wakati = True
        elif o in ("-s","--space"):
            mode["s"] = True
        elif o in ["-S","--separator"]:
            mode["S"] = a
        elif o == "-r":
            if a in romanvals.keys():
                mode['r'] = romanvals[a]
        elif o in ("-J","-H","-K","-E","-a"):
            if a in values:
                mode[o[1:]] = a
        elif o in ("-f","-C","-U"):
            mode[o[1:]] = True
        else:
            assert False, "unhandled option"

    if wakati:
        do_wakati(mode, infile, outfile)
    else:
        do_kakasi(mode, infile, outfile)

if __name__ == "__main__":
    sys.exit(main())
