#!/usr/bin/env python3
# summary: Save or restore your desktop's look and layout.
"""starchaser desktop copy: Put my desktop back (Settings > Recovery).

    starchaser desktop copy list         JSON: the saved copies of your desktop's look and layout, newest first
    starchaser desktop copy restore ID   put that copy back (ID from list); a copy of how it is now is saved first
    starchaser desktop copy save --daily   the daily copy (the starchaser-desktop-copy timer runs this); nothing
                                         when one was taken in the last 20 hours or nothing changed since

A copy holds the theme and dark or light, the wallpaper choice, your Customize changes, the taskbar (where it
sits, its size and pieces, kept apps, Today's weather place), the clock, the shortcut profile and your shortcut
changes, your custom shortcuts, and ~/.config/hypr/user.lua. Never your files, apps, add-ons or screens.
Starchaser also saves one before a change to the look, wallpaper, taskbar or shortcuts (at most one an hour).
Copies are in ~/.local/state/starchaser/desktop-copies/. No password is needed: these are your own settings.
"""
import json
import sys
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent))
from starchaser_cli import safe_streams, takes_nothing_after, usage_error  # noqa: E402
import starchaser_desktop_copy as dc  # noqa: E402

PROG = "starchaser desktop copy"


def main(argv) -> int:
    if not argv or argv[0] in ("-h", "--help", "help"):
        print(__doc__.strip())
        return 0
    cmd = argv[0]
    if cmd == "list":
        if len(argv) > 1:
            return takes_nothing_after(PROG, cmd, argv)
        print(json.dumps({"copies": [{k: c[k] for k in ("id", "time", "why", "title")} for c in dc.copies()]}))
        return 0
    if cmd == "restore":
        if len(argv) != 2:
            return usage_error(PROG, "restore takes one copy ID (from list)", "restore ID")
        r = dc.restore(argv[1])
        print(json.dumps(r))
        return 0 if r["ok"] else 1
    if cmd == "save":
        if argv[1:] != ["--daily"]:
            return usage_error(PROG, "save takes --daily", "save --daily")
        dc.save("daily")
        return 0
    return usage_error(PROG, f"unknown command {cmd!r}", "COMMAND [ARG ...]", ("list", "restore", "save"))


if __name__ == "__main__":
    safe_streams()
    sys.exit(main(sys.argv[1:]))
