import sys
from pprint import pprint

import psycopg2


class LP_DB_Client(object):
    def __init__(self, pwd):
        self._conn = psycopg2.connect("""
            host=lunaparkdb01f.db.yandex.net,lunaparkdb01h.db.yandex.net,lunaparkdb01i.db.yandex.net
            port=6432
            dbname=lunaparkdb
            user=lunapark
            password={}
            target_session_attrs=read-write
            sslmode=verify-full
        """.format(pwd))
        self.cursor = self._conn.cursor()

    def get_projects(self):
        self.cursor.execute('SELECT DISTINCT tag FROM Component')
        return [p[0] for p in self.cursor.fetchall() if p[0]]

    def save_metrics(self, filename):
        self.cursor.execute('SELECT id, code from monitoring_metric order by id')
        with open(filename, 'w', encoding='utf-8') as f:
            f.write('metrics = ')
            pprint({k: v for k,v in self.cursor.fetchall()}, f)

    def save_hosts(self, filename):
        self.cursor.execute('SELECT n, host from server order by n')
        with open(filename, 'w', encoding='utf-8') as f:
            f.write('hosts = ')
            pprint({k: v for k,v in self.cursor.fetchall()}, f)

    def save_components(self, filename):
        self.cursor.execute('''
        SELECT DISTINCT component FROM Job where fd > now() - interval \'1.2 year\' order by component
        ''')
        with open(filename, 'w', encoding='utf-8') as f:
            f.write('components_ids = [\n')
            for s in self.cursor.fetchall():
                f.write("  {},\n".format(s[0]))
            f.write(']')


if __name__ == '__main__':
    lpdb = LP_DB_Client(pwd=sys.argv[1])
    lpdb.save_metrics('lp_metrics.py')
    lpdb.save_hosts('lp_hosts.py')
    lpdb.save_components('lp_components.py')
