#!python
# -*- encoding: utf-8 -*-
import sys
import re
import argparse
import logging
import requests
import toml

from bqsqoop import __version__
from bqsqoop.job import Job
from bqsqoop.utils.gcloud.storage import download_file_as_string


p = argparse.ArgumentParser(
    description=__doc__,
    formatter_class=argparse.RawDescriptionHelpFormatter)
p.add_argument(
    "-v", "--version", action="version",
    version="%(prog)s " + __version__,
    help="Show version and exit.")
p.add_argument(
    "-c", "--config_file", type=str, required=True,
    help="Toml Config file for the bq-sqoop job." +
    "Can be a local file path or a public http link or a GCS file" +
    "eg, https://storage.googleapis.com/sample_config.toml " +
    "or gs://gcs_bucket/sample_config.toml " +
    "or /tmp/sample_config.toml")
p.add_argument(
    "-d", "--debug", dest="debug_mode", action="store_true",
    help="Debug mode on.")


def _read_from_url(url):
    print("Reading config from URL %s" % url)
    resp = requests.get(url=url)
    return toml.loads(resp.text)


def _read_from_gcs(gcs_path):
    print("Reading config from GCS %s" % gcs_path)
    content = download_file_as_string(gcs_path)
    return toml.loads(content.decode("utf-8"))


def _get_configs(config_path):
    http_regex = r"^https?:\/\/.+.toml$"
    gcs_regex = r"^gs:\/\/.+.toml$"
    if re.match(http_regex, config_path):
        return _read_from_url(config_path)
    elif re.match(gcs_regex, config_path):
        return _read_from_gcs(config_path)
    else:
        print("Reading config from local file %s" % config_path)
        return toml.load(config_path)


if __name__ == "__main__":
    if len(sys.argv) == 1:
        p.print_help()
        exit()
    _opts = p.parse_args()

    _configs = _get_configs(_opts.config_file)
    _ = Job(_configs, debug_mode=_opts.debug_mode).execute()
