import logging
import os
from typing import Dict, List, Any
from dateutil import parser as dateparser
from airflow.settings import conf

from zenyatta.common.util import run_command
from zenyatta.common import get_work_directory
from zenyatta.common.errors import ZenyattaError


def pick_date_from_backups(task_date, backups):
    for backup, date in backups:
        date = dateparser.parse(date)
        if date.tzinfo:
            # so we can do a subtraction
            task_date = task_date.replace(tzinfo=date.tzinfo)
        delta = task_date - date
        logging.info("date: {date} - task_date: {task_date} = {delta.days}".format(**locals()))
        if delta.days < 1:
            minutes = delta.seconds / 60.0
            hours = minutes / 60.0
            if hours < 24:
                recovery_date = task_date.strftime("%Y-%m-%dT%H:%M:%S UTC")
                return recovery_date, backup
    return


def parse_wal_backup(to_parse):
    if type(to_parse) is bytes:
        to_parse = to_parse.decode()

    # the [1:] at the end drops the header line
    return [result.split()[0:2] for result in to_parse.split('\n') if result.split()][1:]


def wal_backup_command(aws_meta: Dict[str, str], output_directory: str, ts_nodash: str,
                       env: Dict[Any, Any]) -> List[str]:
    wale = run_command(['which', 'wal-e'], env=env).decode().split('\n')[0]
    output = run_command([wale, "--aws-instance-profile",
                          "backup-list"], env=env)
    backups = parse_wal_backup(output)

    logging.info("available backups: {backups}".format(**locals()))

    task_date = dateparser.parse(ts_nodash)
    # validate we set recovery_date
    recovery_date, the_backup = pick_date_from_backups(task_date, backups[1:])
    if not recovery_date:
        raise ZenyattaError("couldn't set recovery_date for some reason")
    dags_folder = conf.get('core', 'dags_folder')
    zenyatta_dir = os.path.abspath(os.path.join(os.path.join(dags_folder, os.pardir), os.pardir))
    local_vars = locals()
    unformatted = ["{zenyatta_dir}/scripts/setup-postgres-dir.sh",
                   "9.5",
                   "{aws_meta[region]}",
                   "{aws_meta[bucket]}",
                   "'{recovery_date}'",
                   "{the_backup}",
                   "{output_directory}"]

    return [u.format(**local_vars) for u in unformatted]
