from io import BytesIO
import os
import polars as pl
import gzip
from cameo_claw.functional import it_mp_f
from cameo_claw.net import requests_get
import warnings

warnings.filterwarnings("ignore")


def a_distinct(url, target_directory, lst_distinct_column):
    def write(bytes1):
        df = pl_read_csv(bytes1)
        df = df.distinct(subset=lst_distinct_column)
        return bytesio_to_gzip(df, url, target_directory)

    return requests_get_write(target_directory, url, write)


def it_distinct(lst_url, target_directory, lst_distinct_column):
    return it_mp_f(a_distinct, [tuple([url, target_directory, lst_distinct_column]) for url in lst_url])


def bytesio_to_gzip(df, url, target_directory):
    bytesio, filename = prepare_bytesio_filename(df, url)
    path = f'{target_directory}{filename}.csv.gz'
    write_gzip(bytesio, path)
    return url


def pl_read_csv(bytes1):
    df = pl.read_csv(bytes1, infer_schema_length=20000)
    return df


def a_filter(url, target_directory, lst_distinct_column, lst_column_match=[], sort_column=''):
    def write(bytes1):
        df = pl_read_csv(bytes1)
        condition = ''
        for lst_col_val in lst_column_match:
            condition += f"""(pl.col('{lst_col_val[0]}')=='{lst_col_val[1]}') | """
        condition = condition[:-3]
        df = df.filter(eval(condition))
        df = df.distinct(subset=lst_distinct_column)
        if sort_column:
            df = df.sort(sort_column)
        bytesio_to_gzip(df, url, target_directory)
        return url

    return requests_get_write(target_directory, url, write)


def requests_get_write(target_directory, url, f_write):
    try:
        requests_get(f_write, url, target_directory)
    except Exception as e:
        print(f'cameo_claw.py,requests_get_write,Exception:{e, url}')
    return url


def it_filter(lst_url, target_directory, lst_distinct_column, dic_column_match, sort_column):
    return it_mp_f(a_filter,
                   [tuple([url, target_directory, lst_distinct_column,
                           dic_column_match, sort_column]) for url in lst_url])


def a_download(url, target_directory):
    def write(bytes1):
        filename = os.path.basename(url)
        path = f'{target_directory}{filename}'
        with open(path, 'wb') as f:
            f.write(bytes1)
        return url

    return requests_get_write(target_directory, url, write)


def it_download(lst_url, target_directory):
    return it_mp_f(a_download, [tuple([url, target_directory]) for url in lst_url])


def prepare_bytesio_filename(df, url):
    bytesio = BytesIO()
    df.to_csv(bytesio)
    filename = os.path.basename(url)
    filename = filename[:filename.find('.')]
    return bytesio, filename


def a_group(url, target_directory, lst_distinct_column, lst_group_by_column):
    def write(bytes1):
        df = pl_read_csv(bytes1)
        df = df.distinct(subset=lst_distinct_column)
        g = df.groupby(lst_group_by_column)
        for df in g:
            filename_tail = '_group_' + '-'.join(list(
                map(lambda column:
                    str(df.row(0)[df.find_idx_by_name(column)]).replace('_', '-'),
                    lst_group_by_column)))
            bytesio, filename = prepare_bytesio_filename(df, url)
            path = f'{target_directory}{filename}{filename_tail}.csv.gz'
            write_gzip(bytesio, path)
        return url

    return requests_get_write(target_directory, url, write)


def write_gzip(bytesio, path):
    with gzip.open(path, 'wb') as f:
        f.write(bytesio.getvalue())


def it_group(lst_url, target_directory, lst_distinct_column, lst_group_by_column):
    return it_mp_f(a_group,
                   [tuple([url, target_directory, lst_distinct_column, lst_group_by_column]) for url in lst_url])
