from .spec import PluginSpec

MANIFEST_FILE = "manifest.txt"
BLACKLIST_FILE = "blacklist.txt"
PKGS_FILE = "default.nix"
JSON_FILE = ".plugins.json"
PLUGINS_LIST_FILE = "plugins.md"


def get_const(const: str, plug_dir: str) -> str:
    out = plug_dir + "/" + const
    return out


def read_manifest(plug_dir: str) -> list[str]:
    with open(get_const(MANIFEST_FILE, plug_dir), "r") as file:
        specs = set([spec.strip() for spec in file.readlines()])

    return sorted(specs)


def read_manifest_to_spec(plug_dir: str) -> list[PluginSpec]:
    manifest = read_manifest(plug_dir)
    specs = [PluginSpec.from_spec(spec.strip()) for spec in manifest]

    return sorted(specs)


def read_blacklist(plug_dir: str) -> list[str]:
    with open(get_const(BLACKLIST_FILE, plug_dir), "r") as file:
        if len(file.readlines()) == 0:
            return [""]
        else:
            blacklisted_specs = set([spec.strip() for spec in file.readlines()])

    return sorted(blacklisted_specs)


def read_blacklist_to_spec(plug_dir: str) -> list[PluginSpec]:
    blacklist = read_blacklist(plug_dir)
    specs = [PluginSpec.from_spec(spec.strip()) for spec in blacklist]

    return sorted(specs)


def write_manifest(specs: list[str] | set[str], plug_dir: str):
    """write specs to manifest file. Does some cleaning up"""

    with open(get_const(MANIFEST_FILE, plug_dir), "w") as file:
        specs = sorted(set(specs), key=lambda x: x.lower())
        specs = [p for p in specs]

        for s in specs:
            file.write(f"{s}\n")


def write_manifest_from_spec(specs: list[PluginSpec], plug_dir: str):
    """write specs to manifest file. Does some cleaning up"""

    strings = [f"{spec}" for spec in specs]
    write_manifest(strings, plug_dir)