#!/usr/bin/env python3
"""Add or remove a folder in the COSMIC Files sidebar.

COSMIC Files keeps the sidebar's places in its cosmic-config setting
"favorites": ~/.config/cosmic/com.system76.CosmicFiles/v1/favorites, a RON
list such as [Home, Documents, Path("/mnt/x"), Named(path: "/mnt/y", name: "y")].
COSMIC Files watches the file, so a change shows at once. This adds a folder
as Named (a path with the name to show), which COSMIC Files has had since
epoch 1.7, and leaves the rest of the list as it is. Without the file, COSMIC
Files uses its defaults, so those are written first.

Usage:
  cosmic-favorites has <path>
  cosmic-favorites add <path> <name>
  cosmic-favorites remove <path>
"""

import os
import sys

CONFIG = os.path.join(os.environ.get("XDG_CONFIG_HOME") or os.path.expanduser("~/.config"),
                      "cosmic/com.system76.CosmicFiles/v1/favorites")
DEFAULTS = ["Home", "Documents", "Downloads", "Music", "Pictures", "Videos"]


def split_items(text):
    """The top-level items of a RON list, as text."""
    text = text.strip()
    if not (text.startswith("[") and text.endswith("]")):
        raise ValueError("not a RON list")
    items, depth, start, quoted, escaped = [], 0, 1, False, False
    for i, ch in enumerate(text[1:-1], 1):
        if quoted:
            if escaped:
                escaped = False
            elif ch == "\\":
                escaped = True
            elif ch == '"':
                quoted = False
        elif ch == '"':
            quoted = True
        elif ch in "([{":
            depth += 1
        elif ch in ")]}":
            depth -= 1
        elif ch == "," and depth == 0:
            items.append(text[start:i].strip())
            start = i + 1
    last = text[start:-1].strip()
    if last:
        items.append(last)
    return [item for item in items if item]


def ron_string(value):
    return '"' + value.replace("\\", "\\\\").replace('"', '\\"') + '"'


def unquote(value):
    out, escaped = [], False
    for ch in value[1:-1]:
        if escaped:
            out.append(ch)
            escaped = False
        elif ch == "\\":
            escaped = True
        else:
            out.append(ch)
    return "".join(out)


def item_path(item):
    """The path of a Path, Named or Network item, or None."""
    for prefix in ("Path(", "Named(", "Network("):
        if not item.startswith(prefix):
            continue
        body = item[len(prefix):-1].strip().rstrip(",")
        if prefix == "Path(":
            return unquote(body.strip())
        for field in split_items("[" + body + "]"):
            key, _, value = field.partition(":")
            if key.strip() == "path":
                return unquote(value.strip())
    return None


def load():
    try:
        with open(CONFIG, encoding="utf-8") as f:
            return split_items(f.read())
    except FileNotFoundError:
        return list(DEFAULTS)


def save(items):
    os.makedirs(os.path.dirname(CONFIG), exist_ok=True)
    tmp = CONFIG + ".tmp"
    with open(tmp, "w", encoding="utf-8") as f:
        f.write("[\n" + "".join(f"    {item},\n" for item in items) + "]")
    os.replace(tmp, CONFIG)


def main():
    args = sys.argv[1:]
    if len(args) == 2 and args[0] == "has":
        return 0 if any(item_path(i) == args[1] for i in load()) else 1
    if len(args) == 3 and args[0] == "add":
        items = [i for i in load() if item_path(i) != args[1]]
        items.append(f"Named(path: {ron_string(args[1])}, name: {ron_string(args[2])})")
        save(items)
        return 0
    if len(args) == 2 and args[0] == "remove":
        items = load()
        kept = [i for i in items if item_path(i) != args[1]]
        if kept != items:
            save(kept)
        return 0
    print(__doc__.strip().split("\n\n")[-1], file=sys.stderr)
    return 2


if __name__ == "__main__":
    try:
        sys.exit(main())
    except (OSError, ValueError) as error:
        print(f"COSMIC Files sidebar: {error}", file=sys.stderr)
        sys.exit(1)
