from maps.wikimap.stat.dump_to_yt.lib.args import (
    get_connection_string,
    get_parser
)
from maps.wikimap.stat.dump_to_yt.lib.dumper import Dumper

import yt.wrapper as yt

import datetime
import logging


DUMP_DESCRIPTIONS = {
    "social.task_closed": {
        "schema": [
            {"name": "event_id",                   "type": "uint64"},
            {"name": "commit_id",                  "type": "uint64"},
            {"name": "resolved_by",                "type": "uint64"},
            {"name": "resolved_at",                "type": "string"},
            {"name": "resolve_resolution",         "type": "string"},
            {"name": "closed_by",                  "type": "uint64"},
            {"name": "closed_at",                  "type": "string"},
            {"name": "close_resolution",           "type": "string"},
            {"name": "locked_by",                  "type": "uint64"},
            {"name": "locked_at",                  "type": "string"},
            {"name": "created_at",                 "type": "string"},
            {"name": "primary_object_category_id", "type": "string"},
            {"name": "type",                       "type": "string"},
            {"name": "is_created_by_novice",       "type": "boolean"}
        ],
        "query": """
            SELECT
                event_id,
                commit_id,
                resolved_by,
                resolved_at::TEXT,
                resolve_resolution,
                closed_by,
                closed_at::TEXT,
                close_resolution,
                locked_by,
                locked_at::TEXT,
                created_at::TEXT,
                primary_object_category_id,
                type,
                is_created_by_novice
            FROM social.task_closed
            WHERE TRUE
        """,
        "batch": {
            "column": "event_id",
            "size": 100000,
            "start_value": 0
        }
    },
    "social.commit_event": {
        "schema": [
            {"name": "event_id",                   "type": "uint64"},
            {"name": "created_by",                 "type": "uint64"},
            {"name": "created_at",                 "type": "string"},
            {"name": "branch_id",                  "type": "uint64"},
            {"name": "commit_id",                  "type": "uint64"},
            {"name": "action",                     "type": "string"},
            {"name": "bounds",                     "type": "string"},
            {"name": "primary_object_id",          "type": "uint64"},
            {"name": "primary_object_category_id", "type": "string"},
            {"name": "primary_object_label",       "type": "string"},
            {"name": "primary_object_notes",       "type": "string"},
            {"name": "type",                       "type": "string"}
        ],
        "query": """
            SELECT
                event_id,
                created_by,
                created_at::TEXT,
                branch_id,
                commit_id,
                action,
                bounds,
                primary_object_id,
                primary_object_category_id,
                primary_object_label,
                primary_object_notes,
                type
            FROM social.commit_event
            WHERE TRUE
        """,
        "batch": {
            "column": "event_id",
            "size": 100000,
            "start_value": 0
        }
    }
}


def get_logger():
    logging.basicConfig(
        level=logging.INFO,
        format='%(asctime)s %(message)s'
    )
    return logging.getLogger("main-logger")


def get_yt_table_path(yt_dir):
    yesterday = datetime.datetime.utcnow() - datetime.timedelta(days=1)
    return yt.ypath.ypath_join(
        yt_dir,
        yesterday.strftime("%Y-%m-%d"),
    )


def get_yt_link_path(yt_dir):
    return yt.ypath.ypath_join(yt_dir, "latest")


def parse_args():
    parser = get_parser()
    parser.add_argument(
        "--table-name",
        help="Table to dump.",
        required=True,
        choices=DUMP_DESCRIPTIONS.keys()
    )
    return parser.parse_args()


def main():
    logger = get_logger()
    args = parse_args()

    dump_description = DUMP_DESCRIPTIONS[args.table_name]

    dumper = Dumper(
        get_connection_string(args),
        yt.YtClient("hahn", config=yt.default_config.get_config_from_env()),
        logger
    )
    dumper.dump(
        dump_description["query"],
        get_yt_table_path(args.yt_dir),
        dump_description["schema"],
        datetime.timedelta(minutes=args.ttl_minutes),
        yt_link_path=get_yt_link_path(args.yt_dir),
        batch=dump_description["batch"]
    )
