
import json

from cytoolz import thread_first
from cytoolz import thread_last
from m2m.api import ard_entityids
from m2m.api import ard_order_ids


def remove_duplicates(prods: list[dict]) -> list[dict]:
    return thread_first(
        [tuple(d.items()) for d in prods],
        set,
        list,
        lambda x: [dict(t) for t in x]
    )


def create_product_list(api, h, v, region) -> list[dict]:
    return thread_last(
        ard_entityids(api, region, h, v),
        (ard_order_ids, api),
        remove_duplicates
    )


def product_list_path(fs, h, v, region, outroot) -> str:
    return f"{outroot}{fs.sep}{region}-{h}-{v}-manifest.json"


def load_product_list(fs, filepath) -> list[dict]:
    with fs.open(filepath, "rb") as f:
        return remove_duplicates(json.loads(f.read()))


def save_product_list(fs, data, filepath) -> None:
    with fs.open(filepath, 'w') as f:
        f.write(json.dumps(data))


def ceph_w(fs, data, **kwargs):
    kwargs["outroot"] = "usgs-landsat-ard/collection02/manifest"
    save_product_list(fs, data, product_list_path(fs, **kwargs))


def ceph_r(fs, **kwargs):
    kwargs["outroot"] = "usgs-landsat-ard/collection02/manifest"
    return load_product_list(fs, product_list_path(fs, **kwargs))


def local_w(fs, data, **kwargs):
    save_product_list(fs, data, product_list_path(fs, **kwargs))


def local_r(fs, **kwargs):
    return load_product_list(fs, product_list_path(fs, **kwargs))
