<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
 def origin(hosts):
 """ Return a function that returns a valid HTTP Origin or localhost if none found. """


    hosts = [urlsplit(h) for h in hosts]

    def func(environ):
        if 'ISSO_CORS_ORIGIN' in environ:
            return environ['ISSO_CORS_ORIGIN']

        if not hosts:
            return "http://invalid.local"

        loc = environ.get("HTTP_ORIGIN", environ.get("HTTP_REFERER", None))

        if loc is None:
            return urljoin(*hosts[0])

        for split in hosts:
            if urlsplit(loc) == split:
                return urljoin(*split)
        else:
            return urljoin(*hosts[0])

    return func