#!/usr/bin/env python

"""
CLI interface to REDbot
"""

__author__ = "Jerome Renard <jerome.renard@gmail.com>"

from configparser import ConfigParser
from optparse import OptionParser
import sys

import thor

from redbot import __version__
from redbot.formatter import find_formatter, available_formatters
from redbot.resource import HttpResource


def main() -> None:
    usage = """Usage: %prog [options] <url>"""
    version = """Redbot version %s, http://redbot.org/ """ % __version__

    opt_parser = OptionParser(usage=usage, version=version)
    opt_parser.set_defaults(
        version=False, descend=False, output_format="text", show_recommendations=False
    )

    opt_parser.add_option(
        "-a",
        "--assets",
        action="store_true",
        dest="descend",
        help="check assets, if the URL contains HTML",
    )
    opt_parser.add_option(
        "-o",
        "--output-format",
        action="store",
        dest="output_format",
        help="one of: %s" % ", ".join(available_formatters()),
    )

    (options, args) = opt_parser.parse_args()

    if len(args) != 1:
        opt_parser.error("Please specify a URL.")

    if options.output_format not in available_formatters():
        opt_parser.error("Unrecognised output format.")

    url = args[0]

    parser = ConfigParser()
    parser.read_dict({"redbot": {"lang": "en", "charset": "utf-8"}})
    config = parser["redbot"]

    resource = HttpResource(config, descend=options.descend)
    resource.set_request(url)

    formatter = find_formatter(options.output_format, "text", options.descend)(
        config, resource, output, tty_out=sys.stdout.isatty(), descend=options.descend
    )

    formatter.bind_resource(resource)

    @thor.events.on(formatter)
    def formatter_done() -> None:
        thor.stop()

    resource.check()
    thor.run()


def output(out: str) -> None:
    sys.stdout.write(out)


if __name__ == "__main__":
    main()
