# implements synchronization of sellerlogic data

import csv
import urllib

from collections import Counter, defaultdict
from datetime import datetime
from itertools import zip_longest
from logging import debug, error, warning, info
from pathlib import Path

from ..config import *


def cmd_calculate_price_changes(args):
    filenames = Path(SELLERLOGICCACHE).glob(f"{SELLERLOGICFILENAME}*.csv")
    lastprice = defaultdict(float)
    counter = Counter()
    for fname in sorted(filenames):
        changed = []
        with open(fname, newline='') as f:
            data = f.read().split('\n')[2:]
            reader = csv.DictReader(data, delimiter=';')
            for row in reader:
                sku = row['item_sku']
                price = float(row['price'])
                if lastprice[sku] != price:
                    changed.append(sku)
                lastprice[sku] = price
        counter.update(changed)
    allchanges = [m for m in counter.most_common() if m[1] > 1]
    for c in allchanges:
        print(f"{c[0]}: {c[1]}")
    print(f"Affected SKUs: {len(allchanges)}")


def cmd_collect(args):
    timestamp = datetime.now().strftime('%Y%m%d%H%M%S')
    filename = SELLERLOGICFILENAME + f"-{timestamp}.csv"
    outpath = Path(SELLERLOGICCACHE, filename)
    urllib.request.urlretrieve(SELLERLOCICPRICEURL, outpath)
