#!/usr/bin/env python


import sys
import argparse
from pathlib import Path
from bandcampsync import version, logger, do_sync


log = logger.get_logger('run')


if __name__ == '__main__':
    parser = argparse.ArgumentParser(
        prog='bandcampsync',
        description='Syncs media purcahsed on bandcamp.com with a local directory',
    )
    parser.add_argument('-v', '--version', action='store_true',
        help='Displays the bandcampsync version and exits')
    parser.add_argument('-c', '--cookies', required=True,
        help='Path to the cookies file')
    parser.add_argument('-d', '--directory', required=True,
        help='Path to the directory to download media to')
    parser.add_argument('-i', '--ignore', default='',
        help='A space-delimited list of patterns matching artists to bypass')
    parser.add_argument('-f', '--format', default='flac',
        help='Media format to download, defaults to "flac"')
    parser.add_argument('-t', '--temp-dir', default='',
        help='Path to use for temporary downloads')
    parser.add_argument('-n', '--notify-url', default='',
        help='URL to notify with a GET request when any new downloads have completed')
    args = parser.parse_args()
    if args.version:
        print(f'BandcampSync version: {version}', file=sys.stdout)
        sys.exit(0)
    cookies_path = Path(args.cookies).resolve()
    dir_path = Path(args.directory).resolve()
    ign_patterns = args.ignore
    media_format = args.format
    if not cookies_path.is_file():
        raise ValueError(f'Cookies file does not exist: {cookies_path}')
    if not dir_path.is_dir():
        raise ValueError(f'Directory does not exist: {dir_path}')
    if args.ignore:
        patterns = args.ignore
        log.warning(f'BandcampSync is bypassing: {patterns}')
    if args.temp_dir:
        temp_dir = Path(args.temp_dir).resolve()
        if not temp_dir.is_dir():
            raise ValueError(f'Temporary directory does not exist: {temp_dir}')
    else:
        temp_dir = None
    if args.notify_url:
        notify_url = args.notify_url
        log.info(f'BandcampSync will notify: {notify_url}')
    else:
        notify_url = None
    log.info(f'BandcampSync v{version} starting')
    with open(cookies_path, 'rt') as f:
        cookies = f.read().strip()
    log.info(f'Loaded cookies from "{cookies_path}"')
    do_sync(cookies_path, cookies, dir_path, media_format, temp_dir, ign_patterns, notify_url)
    log.info(f'Done')
