#!/usr/bin/env python
# -*- coding: utf-8 -*-

import logging
import os

from startrek_client import Startrek
from yt.wrapper.client import Yt
import yt


def main():
    logging.basicConfig(level=logging.INFO, format="[%(asctime)s] %(levelname)s %(thread)d %(message)s")

    UPDATES_ROOT = "//home/webmaster/prod/seocheck/updates"

    client = Yt(proxy="hahn.yt.yandex.net", config={"token_path": os.getenv("YT_TOKEN_PATH")})
    st_client = Startrek(token=os.getenv("STARTREK_TOKEN"), useragent="webmaster-cm")

    with client.Transaction():
        for table in client.search(UPDATES_ROOT, node_type="table"):
            for line in client.read_table(table, raw=False, format=yt.wrapper.JsonFormat(attributes={"encode_utf8": True})):
                content = (
                    "ФИО: {}\n"
                    "CandidateId: {}\n"
                    "AttachmentId: {}\n"
                    # "Маркеры: где={}, как={}, кто={}, что={}\n"
                    "Резюме: (({} ссылка)) {}\n"
                    "Ответственные: {}\n"
                    "Экспорт: {}\n"
                ).format(
                    line["FullName"],
                    line["CandidateId"],
                    line["AttachmentId"],
                    # line["HitsWhere"], line["HitsHow"], line["HitsWho"], line["HitsWhat"],
                    line["MDSLink"], "добавил: кто:" + line["Uploader"] if line["Uploader"] else "",
                    " ".join(map(lambda x: "кто:" + x, line["Responsibles"].split(","))),
                    line["SourceTable"]
                )

                summary = "{} [cid:{} aid:{}]".format(line["FullName"], line["CandidateId"], line["AttachmentId"])
                ticket = st_client.issues.create(
                    queue="SEOCHECK",
                    summary=summary,
                    description=content,
                    assignee="slivinskiy",
                    components=[62791],
                    duplicatesCount=line["HitsTotal"]
                )

                logging.info(ticket.key)

            client.remove(table)

if __name__ == "__main__":
    main()
