#!/usr/bin/env python3
"""Install missing GNOME Terminal color profiles -- Solarized Dark,
Solarized Light, Spacedust -- plus a "1-Spacedust" duplicate that sorts to
the top of the profile list/menu (GNOME Terminal sorts profiles by
visible-name, not list order) -- via dconf, and set Spacedust as the
default profile.

Color values from Gogh (https://github.com/Gogh-Co/Gogh, data/themes.json).
Not using bin/gogh itself for this: its BASE_URL points at the old
Mayccoll/Gogh repo, which now 301-redirects to Gogh-Co/Gogh with a
completely different data layout (JSON-based, no more per-theme shell
scripts to download) -- so bin/gogh's download step is broken upstream.

Idempotent: skips any profile whose visible-name already exists, safe to
run every login.
"""
import ast
import subprocess
import uuid as uuidlib

PROFILES = "/org/gnome/terminal/legacy/profiles:"

THEMES = {
    "Solarized Dark": {
        "background": "#002B36", "foreground": "#839496", "cursor": "#839496",
        "palette": ["#073642", "#DC322F", "#859900", "#CF9A6B", "#268BD2", "#D33682",
                    "#2AA198", "#EEE8D5", "#657B83", "#CB4B16", "#859900", "#CF9A6B",
                    "#6c71c4", "#D33682", "#2AA198", "#FDF6E3"],
    },
    "Solarized Light": {
        "background": "#FDF6E3", "foreground": "#657B83", "cursor": "#657B83",
        "palette": ["#EEE8D5", "#DC322F", "#859900", "#B58900", "#268BD2", "#D33682",
                    "#2AA198", "#002B36", "#657b83", "#CB4B16", "#859900", "#B58900",
                    "#6C71C4", "#D33682", "#2AA198", "#073642"],
    },
    "Spacedust": {
        "background": "#0A1E24", "foreground": "#ECF0C1", "cursor": "#ECF0C1",
        "palette": ["#6E5346", "#E35B00", "#5CAB96", "#E3CD7B", "#0F548B", "#E35B00",
                    "#06AFC7", "#F0F1CE", "#684C31", "#FF8A3A", "#AECAB8", "#FFC878",
                    "#67A0CE", "#FF8A3A", "#83A7B4", "#FEFFF1"],
    },
}
THEMES["1-Spacedust"] = THEMES["Spacedust"]


def dconf_read(path):
    return subprocess.run(
        ["dconf", "read", path], capture_output=True, text=True
    ).stdout.strip()


def dconf_write(path, value):
    subprocess.run(["dconf", "write", path, value], check=True)


def existing_profiles():
    """{visible_name: uuid} for every profile currently in the list."""
    raw = dconf_read(f"{PROFILES}/list")
    uuids = ast.literal_eval(raw) if raw else []
    result = {}
    for u in uuids:
        name = dconf_read(f"{PROFILES}/:{u}/visible-name")
        if name:
            result[ast.literal_eval(name)] = u
    return result


def add_to_list(new_uuid):
    raw = dconf_read(f"{PROFILES}/list")
    uuids = ast.literal_eval(raw) if raw else []
    uuids.append(new_uuid)
    dconf_write(f"{PROFILES}/list", repr(uuids))


def create_profile(name, colors):
    new_uuid = str(uuidlib.uuid4())
    add_to_list(new_uuid)
    base = f"{PROFILES}/:{new_uuid}"
    dconf_write(f"{base}/visible-name", repr(name))
    dconf_write(f"{base}/use-theme-colors", "false")
    dconf_write(f"{base}/background-color", repr(colors["background"]))
    dconf_write(f"{base}/foreground-color", repr(colors["foreground"]))
    dconf_write(f"{base}/cursor-colors-set", "true")
    dconf_write(f"{base}/cursor-background-color", repr(colors["cursor"]))
    dconf_write(f"{base}/cursor-foreground-color", repr(colors["background"]))
    dconf_write(f"{base}/palette", repr(colors["palette"]))
    return new_uuid


def main():
    current = existing_profiles()
    for name, colors in THEMES.items():
        if name in current:
            print(f"install_terminal_profiles: '{name}' already exists, skipping")
            continue
        new_uuid = create_profile(name, colors)
        print(f"install_terminal_profiles: created '{name}' ({new_uuid})")
        current[name] = new_uuid

    default_uuid = current["Spacedust"]
    dconf_write(f"{PROFILES}/default", repr(default_uuid))
    print(f"install_terminal_profiles: default profile set to Spacedust ({default_uuid})")


if __name__ == "__main__":
    main()
